[英]Return HTML tag in array of object map
I have an array of objects mapping to return as a component but some of the content has an HTML tag.我有一个映射对象数组作为组件返回,但其中一些内容具有 HTML 标记。 How can I return it rendering the HTML tag inside it?
我怎样才能返回它呈现其中的 HTML 标签?
const listContent = [
{
title: 'Sample Title 1',
content: 'Sample of only text here'
},
{
title: 'Sample Title 2',
content: 'Sample of only text here with <span>Should render as span</span>'
},
];
{listItemContent.map(item => (
<ListItem>
<h1>{item.title}</h1>
<p>{item.content}</p>
</ListItem>
))}
You probably want to use React fragments , like so:你可能想使用React fragment ,像这样:
const listContent = [
{
title: 'Sample Title 1',
content: 'Sample of only text here'
},
{
title: 'Sample Title 2',
content: <>
Sample of only text here with <span>Should render as span</span>
</>
},
];
...
{listItemContent.map(item => (
<ListItem key={item.key}>
<h1>{item.title}</h1>
<p>{item.content}</p>
</ListItem>
))}
Note that you should ideally also add a key
to each React element of an array.请注意,理想情况下,您还应该为数组的每个 React 元素添加一个
key
。
You might want to use react's dangerouslySetInnerHTML你可能想使用 react 的危险的SetInnerHTML
{listItemContent.map(item => (
<ListItem key={item.key}>
<h1>{item.title}</h1>
<p dangerouslySetInnerHTML={{__html: item.content}} />
</ListItem>
))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.