简体   繁体   English

将字符串转换为 React JSX

[英]Convert string to React JSX

Goal: I want to convert strings including React components into fully-functional JSX.目标:我想将包含 React 组件的字符串转换为功能齐全的 JSX。

The easier example, for which there are many solutions on Stack Overflow, is this:在 Stack Overflow 上有很多解决方案的更简单的例子是:

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/>";但如果相反, let txt = "<MyComponent/>"; , where MyComponent is a custom React component, I cannot find a way for the browser to interpret that correctly. ,其中 MyComponent 是自定义 React 组件,我找不到浏览器正确解释它的方法。

Using some methods, it will enter the DOM as lowercase <mycomponent><mycomponent/> .使用一些方法,它会以小写的<mycomponent><mycomponent/>进入 DOM。 With other tricks, I can get it into the DOM as uppercase <MyComponent><MyComponent/> .使用其他技巧,我可以将它作为大写的<MyComponent><MyComponent/>放入 DOM 中。 But the browser will not interpret MyComponent as a React component, and will not execute the code inside.但是浏览器不会将 MyComponent 解释为 React 组件,也不会执行里面的代码。

I'm not interested in the answer React.createElement() because I don't want to use this for one component at a time.我对答案React.createElement()不感兴趣,因为我不想一次将它用于一个组件。 I want to parse long strings of JSX.我想解析 JSX 的长字符串。

There is no library which parses a string containing custom React component .没有解析包含自定义 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.此外,组件的实际名称在 React 中是没有意义的,您必须在作用域中提供它的实例。

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.你可以使用ReactDOMServer因此你有元素实例来呈现它的 HTML。

You can use -您可以使用 -

  • html-react-parser html-反应解析器
  • react-jsx-parser react-jsx-解析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM