我环顾四周,找不到任何有关此的信息。我的问题是这个。当我有这样的 react 代码时:
<p ref="description" className="description" dangerouslySetInnerHTML={{__html: this.props.description}}></p>
和
this.props.description = "<p>this is a test</p>";
通过 dangerouslySetInnerHTML 添加的 html 并没有添加到这样的描述下:
<p class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;"></p>
<p>this is a test</p>
这似乎只发生在传递给 dangerouslySetInnerHTML 的字符串包含 block 级元素时。如果传递的字符串是:
this.props.description = "<span>this is a test</span>";
它工作正常并输出:
<p class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;">
<span>this is a test</span>
</p>
如果我更改代码,所以我使用 div 标签而不是像这样的 p 标签:
<div ref="description" className="description" dangerouslySetInnerHTML={{__html: this.props.description}}></div>
然后 dangerouslySetInnerHTML 与 block 级元素一起正常工作并输出:
<div class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;">
<p>this is a test</p>
</div>
最佳答案
React 没有这样做,你的浏览器是。把 <p>
另一个内的元素<p>
元素不是有效的 HTML†,因此您的浏览器会做唯一有意义的事情,即放置第二个 <p>
在第一个之后。
您可以在此代码段中看到完全相同的行为,它不使用任何 JavaScript:
p { width: 10em; height: 1em; }
#outer { border: 1px solid blue; }
#inner { border: 1px solid green; }
<p id="outer">
<p id="inner">Hello</p>
</p>
†在 HTML5 规范中,
<p>
元素的内容模型被命名为“短语内容”:Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level.
Take a look at the spec对于
<p>
中有效的元素列表元素。
关于javascript - React dangerouslySetInnerHTML 只有在 div 标签上使用时才能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31348533/