简体   繁体   English

使用变量时危险地反应SetInnerHTML不起作用

[英]React dangerouslySetInnerHTML not working when using variable

I'm creating an SPA using React that searches data and displays results. 我正在使用React创建一个SPA,以搜索数据并显示结果。 Each result follows the following model 每个结果遵循以下模型

{
  "title": "A Title",
  "body": " <li>escaped html <strong>that sould be rendered</strong>.</li>
    </ul>"
}

The body property is always an escaped html that should be rendered in a component. body属性始终是应在组件中呈现的转义html。 This component looks like this: 该组件如下所示:

Code

function SearchResult({ title, body, favourite }) {
  return (
    <article className="SearchResult">
    <section>
      <i className={`icon-star${favourite ? ' marked' : ''}`} />
      {title}
    </section>
    <section
      dangerouslySetInnerHTML={{ __html: body }}
      className="SearchResult-body"
    />
  </article>
  );
}

but the body of each result is not being rendered correctly, instead, it shows the html as a text 但是每个结果的主体都无法正确呈现,而是将html显示为文本 在此处输入图片说明 在此处输入图片说明

The issue is that it only happens when I create the component passing a variable to the body property 问题是,仅当我创建将变量传递给body属性的组件时,它才会发生

results.map((result, index) => (
      <SearchResult key={index} title={result.title} body={result.body} />
    ))

But if I do this, it works fine 但是如果我这样做,那就很好

<SearchResult
    title="A title"
    body=" &lt;li&gt;escaped html&amp;nbsp;&lt;strong&gt;that sould be rendered&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;"
  />

Why is this different? 为什么有什么不同? Is there any preprocessing that I should add to the value before passing it in the property that is added by default when I use the fixed value? 使用固定值时,在将其传递给默认添加的属性之前,是否应该对其进行任何预处理?

Demo 演示版

A demo of this issue can be seen here 可以在此处查看此问题的演示

It seems like this issue only occurs when you give it an escaped html. 似乎仅当您给它转义的html时才会出现此问题

A solution implemented by @sergiotapia involves creating a helper function to unescape the html string to make it work. @sergiotapia实现的解决方案涉及创建一个辅助函数,以取消转义html字符串以使其工作。

htmlDecode(content) {
  let e = document.createElement('div');
  e.innerHTML = content;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
<section
  dangerouslySetInnerHTML={{ __html: htmlDecode(body) }}
  className="SearchResult-body"
/>

However as @brigand mentioned and I'll quote " Unescaping it could allow for XSS attacks and incorrect rendering. " so this might not be the perfect solution for this. 但是,正如@brigand提到的那样,我将引用“ 对其进行转义可能会导致XSS攻击和错误的呈现。 ”因此,这可能不是完美的解决方案。

See working example 参见工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM