【问题标题】:Render text with HTML tags in page [duplicate]在页面中呈现带有 HTML 标记的文本 [重复]
【发布时间】:2020-03-12 21:42:59
【问题描述】:

我有这些数据:

{ 
  "text":"<h1>hello</h1><p style={{backgroundColor:blue}}>Paragraph text</p>",
  "type":"bold"
},

但是当我在我的页面中显示它时,它会显示标签 h1 和 p 以及样式。我怎样才能打印这个变量,并让标签也能正常工作?

这是我的 js:

<div key={index}>
    {descriere.type === "bold" ? (
    <p style={{ color: "red" }}>
        {data.text}
    </p>
    ) : (
    <p style={{ color: "purple" }}>
        {data.text}
    </p>
    )}
</div>

我也尝试在 div 标签内打印它,同样的问题。 有什么想法吗?

【问题讨论】:

    标签: javascript html css reactjs gatsby


    【解决方案1】:

    您可以使用dangerouslySetInnerHTML 属性来呈现HTML。这是working example

    【讨论】:

      【解决方案2】:

      尝试使用dangerouslySetInnerHTML,它广泛用于 gatsby,您可以在其中查询降价内容。

      <div key={index}>
        {descriere.type === 'bold' ? (
          <p style={{ color: 'red' }}>
            <div dangerouslySetInnerHTML={__html: data.text} />
          </p>
        ) : (
          <p style={{ color: 'purple' }}>
            <div dangerouslySetInnerHTML={__html: data.text} />
          </p>
        )}
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-29
        • 2019-08-05
        • 2011-01-13
        • 1970-01-01
        • 2021-10-25
        相关资源
        最近更新 更多