简体   繁体   English

危险地反应SetInnerHTML仅在div标记上使用时才能正常工作

[英]React dangerouslySetInnerHTML Only working correctly when it is used on a div tag

I've looked around and can't find any info on this. 我环顾四周,找不到任何相关信息。 My issue is this. 我的问题是这个。 when i have react code like this: 当我有这样的反应代码:

<p ref="description" className="description" dangerouslySetInnerHTML={{__html: this.props.description}}></p>

and

this.props.description = "<p>this is a test</p>";

the html added via dangerouslySetInnerHTML is added under neither the description like this: 通过dragonallySetInnerHTML添加的html均未添加如下描述:

<p class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;"></p>
<p>this is a test</p>

this seems to only happen when the string passed to dangerouslySetInnerHTML contains a block level element. 这似乎仅在传递给dragonallySetInnerHTML的字符串包含块级元素时才会发生。 if the passed string is: 如果传递的字符串是:

this.props.description = "<span>this is a test</span>";

it works correctly and outputs this: 它可以正常工作并输出以下内容:

<p class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;">
    <span>this is a test</span>
</p>    

if i change the code from so i use a div tag instead of ap tag like this: 如果我更改代码,则使用div标签代替ap标签,如下所示:

<div ref="description" className="description" dangerouslySetInnerHTML={{__html: this.props.description}}></div>

then dangerouslySetInnerHTML works correctly with block level elements and outputs this: 然后危险地将SetInnerHTML与块级元素一起正常工作并输出以下内容:

<div class="description" data-reactid=".0.0.2.2" style="height: 120.639999389649px;">
    <p>this is a test</p>
</div>

React isn't doing this, your browser is. React没有这样做,您的浏览器正在这么做。 Putting a <p> element inside another <p> element isn't valid HTML , so your browser does the only thing that makes sense, which is to put the second <p> after the first. <p>元素放在另一个<p>元素中不是有效的HTML ,因此浏览器所做的唯一有意义的事情是将第二个<p>放在第一个之后。

You can see the exact same behavior in this snippet, which doesn't use any JavaScript: 您可以在此代码段中看到完全相同的行为,该代码段不使用任何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> 

In the HTML5 spec the <p> element's content model is named "Phrasing content": 在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 for a list of elements that are valid inside a <p> element. 查看在 <p>元素内有效的元素列表的规范

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

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