如何呈现以字符串形式存储在ReactJS中的jsx

问题描述 投票:0回答:1

我正在尝试使用自定义组件构建React应用。应用程序的输入是来自API的jsx(作为字符串)。现在,我想呈现此输入jsx(字符串变量),但无法做到这一点。我已经尝试过eval()和dragonedSetInnerHTML选项,但是没有成功。我的JSX字符串看起来像

'<div> <MyComponent attr_1={this.state.array["field"]}></MyComponent> </div>'
reactjs eval render
1个回答
1
投票

此线程应回答您的问题:How to render a string with JSX in React

引用:

您可以使用babel对其进行转换

npm install --save babel-core Then in your code

var babel = require('babel-core'); 
var Component = eval(babel.transform('<div><MyComponent /></div>').code);

请注意,通常将bad idea转换为字符串可执行代码。

© www.soinside.com 2019 - 2024. All rights reserved.