Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

reactjs - Convert string to React JSX

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...