我的常见问题解答组件具有以下状态:
this.state = {
faqs: [
{
question: "Some question string",
answer: "Some answer string"
},
{
question: "Some question string",
answer: "Some answer string"
}
]
};
我遍历到render方法中以显示每个FAQ集。但是,我的“ answer”属性需要包含<p></p>
标记,如下所示:
{
question: "Some question string",
answer: "<p>Some answer string</p> <p>Some answer string</p>"
}
如何在反应中实现这一目标?
答案 0 :(得分:1)
如果我正确理解了您的情况,则可能是React内置的dangerouslySetInnerHTML
道具的一种情况。
dangerouslySetInnerHTML
道具提供了一种机制,用于通过字符串值而不是通过JSX来指定元素的html内容。
要说明此概念,请参见以下代码:
// I am assuming that your render function looks something like this:
function render() {
const faqs = this.state.faqs
return (<div>
faqs.map(faq => {
return (<div>
<h3> {{ faq.question }}</h3>
{/* make use of dangerouslySetInnerHTML in this way to
account for HTML tags/markup in the answer variable */}
<div dangerouslySetInnerHTML={{ _html : faq.answer }}></div>
</div>)
})
</div>)
}
答案 1 :(得分:1)
只需用Fragments包装即可。
{
question: "Some question string",
answer: <><p>Some answer string</p> <p>Some answer string</p></>
}
或与此
{
question: "Some question string",
answer: <React.Fragment><p>Some answer string</p> <p>Some answer string</p></React.Fragment>
}