如何以反应状态将HTML存储为对象属性的值?

时间:2018-08-28 03:00:25

标签: reactjs javascript-objects

我的常见问题解答组件具有以下状态:

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>"
}

如何在反应中实现这一目标?

2 个答案:

答案 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>
}