Convert string to React JSX

落爺英雄遲暮 提交于 2020-11-29 09:14:21

问题


Goal: I want to convert strings including React components into fully-functional JSX.

The easier example, for which there are many solutions on Stack Overflow, is this:

render()
{
  let txt = "<span><b>Hello World!</b></span>";

  return <div dangerouslySetInnerHTML={{__html: txt}}></div>;
    //---OR---
  return ReactHtmlParser(txt); //using react-html-parser
    //---OR---
  return parse(txt); //using html-react-parser
}

But if instead, let txt = "<MyComponent/>";, where MyComponent is a custom React component, I cannot find a way for the browser to interpret that correctly.

Using some methods, it will enter the DOM as lowercase <mycomponent><mycomponent/>. With other tricks, I can get it into the DOM as uppercase <MyComponent><MyComponent/>. But the browser will not interpret MyComponent as a React component, and will not execute the code inside.

I'm not interested in the answer React.createElement() because I don't want to use this for one component at a time. I want to parse long strings of JSX.


回答1:


There is no library which parses a string containing custom React component.

If you think about it, such library needs to be aware of your components locations as it needs to import and render it. Moreover, the actual name of the components is meaningless in React, you must have its instance available in scope.

Therefore your only solution is to write a custom parser for your own.

Such solution will roughly hold a dictionary which maps string to their components (need to handle props and duplicate naming too).

import {MyComponent,Button} from 'components';

export const Components = {
   MyComponent,
   Button
};

myParser('<MyComponent/>'); // Match MyComponent

You can use ReactDOMServer hence you have the element instance to render its HTML.



来源:https://stackoverflow.com/questions/64191372/convert-string-to-react-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!