简体   繁体   English

反应“ dangerouslySetInnerHTML”会在状态更改时导致“不是孩子”错误

[英]React “dangerouslySetInnerHTML” causes “not a child” errors on state change

I have a site which allows users to write content in BBCode and then parses the BBCode to HTML for rendering on the site. 我有一个网站,该网站允许用户使用BBCode编写内容,然后将BBCode解析为HTML以在网站上呈现。 I am converting part of the site to use React. 我正在转换部分站点以使用React。 As far as I know, the only way of rendering raw content in React is to use dangerouslySetInnerHTML={ { __html: someHtmlString } } on a child element. 据我所知,在React中渲染原始内容的唯一方法是在子元素上使用dangerouslySetInnerHTML={ { __html: someHtmlString } }地使用dangerouslySetInnerHTML={ { __html: someHtmlString } }

When I use this method, however, I get errors when removing the node with dangerouslySetInnerHTML or modifying any of its neighbors. 当我用这个方法,但是,我删除与节点时出现错误dangerouslySetInnerHTML或修改其任何邻国。 The errors are either The node before which the new node is to be inserted is not a child of this node or The node to be removed is not a child of this node . 错误可能The node before which the new node is to be inserted is not a child of this node或者The node to be removed is not a child of this node

The Node in question that is not a child of some other node appears to be the <span> tag on which I am "dangerously setting innerHTML", as I inspected it in the debugger and its child nodes are the rendered BBCode. 所讨论的不是其他节点的子节点似乎是<span>标记,我在该标记上“危险地设置innerHTML”,正如我在调试器中检查的那样,其子节点是呈现的BBCode。

Is there a reason why the DOM hierarchy is getting corrupted like this? DOM层次结构被破坏的原因是否如此? Do I need to do a multi-stage update when removing this node to first set its innerHTML to null, then re-render, then remove the node itself? 删除此节点时,首先将其innerHTML设置为null,然后重新渲染, 然后删除该节点本身,是否需要进行多阶段更新?

I believe I found the cause of this...I can't be positive this was the cause, but changing it fixed the issue. 我相信我已经找到了造成这种情况的原因...我不能肯定这是造成原因的原因,但是更改它可以解决问题。

The rendered BBCode appears to have contained elements that are not valid children of a <span> , so when the innerHTML was set, the node somehow just got removed from the DOM hierarchy (even though it rendered completely fine in the browser, with the BBCode content and everything). 呈现的BBCode似乎包含的元素不是<span>有效子元素,因此,在设置innerHTML时,该节点以某种方式刚刚从DOM层次结构中删除(即使使用BBCode在浏览器中呈现了很好的效果)内容和一切)。

I restructured the component to set the innerHTML of the parent <div> (where the editing controls would show up) when not editing, and instead render an identical <div> with the editing contents when the component was in edit mode. 我对组件进行了重组,以在不进行编辑时设置其父<div>innerHTML (将显示编辑控件),而当该组件处于编辑模式时,将呈现与编辑内容相同的<div>

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

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