[英]React - Render HTML from JSON
I am trying to render HTML from JSON into my React component. 我试图将HTML从JSON渲染到我的React组件中。 I am aware of the dangerouslySetInnerHTML and am not looking to use that as I would like to leverage other React components inside of the rendered HTML.
我知道危险的SetInnerHTML,并且不希望使用它,因为我想在渲染的HTML内利用其他React组件。 Currently I can render any element as long as I close the tag.
目前,只要关闭标签,我就可以渲染任何元素。 But this is not the case as in if I would like to put multiple elements or img tags in a div i would need it to remain open until all of the img tags have completed.
但是情况并非如此,好像我想在div中放置多个元素或img标签时,我需要它保持打开状态,直到所有img标签都已完成。 I would appreciate any help on this.
我将不胜感激。 Thanks
谢谢
render(){
var data = [
{
type: 'div',
open: true,
id: 1,
className: 'col-md-12 test',
value: ''
},
{
type: 'div',
open: false,
id: 1
}
]
var elements = data.map(function(element){
if(element.open){
return <element.type className={element.className}>
} else {
return </element.type>
}
})
return (
<div>
{elements}
</div>
)
}
webpack error webpack错误
3 | return <element.type className={element.className}>
34 | } else {
> 35 | return </element.type>
| ^
36 | }
37 | })
38 | return (
@ ./src/index.js 9:11-38
The data structure is redundant; 数据结构是冗余的; you can simply do this:
您可以简单地做到这一点:
render() {
var elements = (
<div id='1' className='col-md-12 test'></div>
);
return (
<div>{elements}</div>
);
}
Element trees themselves are just data. 元素树本身就是数据。 Rather than trying to invent a data structure to represent one, just use JSX.
与其尝试发明一种数据结构来表示一个数据结构,不如使用JSX。
The closing tag
wasn't proper. closing tag
不合适。
check the following fiddle. 检查以下小提琴。
https://jsfiddle.net/pranesh_ravi/mLoL6pzz/ https://jsfiddle.net/pranesh_ravi/mLoL6pzz/
Hope it helps! 希望能帮助到你!
I think @pranesh answered right. 我认为@pranesh回答正确。 It has to go something like this
它必须像这样
var elements = data.map(function(element){
if(element.open){
return <element.type className ={element.className}>Sample</element.type>
} else {
return <element.type>Sample</element.type>
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.