问题描述
目标:我想将包括React组件在内的字符串转换为功能齐全的JSX。
Goal: I want to convert strings including React components into fully-functional JSX.
一个简单的示例,在Stack Overflow上有许多解决方案,是这样:
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
}
但如果相反,请 let txt =< MyComponent />;
,其中MyComponent是自定义的React组件,我找不到浏览器正确解释它的方法。
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.
使用某些方法,它将以小写< mycomponent>< mycomponent />
的形式输入DOM。利用其他技巧,我可以将其作为大写< MyComponent>< MyComponent />
进入DOM。但是浏览器不会将MyComponent解释为React组件,并且不会在其中执行代码。
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.
我对答案 React.createElement()不感兴趣
,因为我不想一次将其用于一个组件。我想解析JSX的长字符串。
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.
推荐答案
没有库可以解析包含自定义React组件的字符串。
如果考虑到这一点,此类库需要知道您的组件位置,因为它需要导入和呈现它。此外,组件的实际名称在React中是没有意义的,您必须在范围内提供其实例。
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
您可以使用,因此您具有元素实例来呈现其HTML。
You can use ReactDOMServer
hence you have the element instance to render its HTML.
这篇关于将字符串转换为React JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!