简体   繁体   English

在React组件之外操纵dom元素

[英]Manipulate dom element outside React component

I have a React component that renders HTML only on a small part of a HTML document. 我有一个React组件,仅在HTML文档的一小部分上呈现HTML。

From within the React component I need to replace an element, that exist outside the component, with a block of HTML. 在React组件内部,我需要用HTML块替换组件外部存在的元素。

No matter how much I'm googling this, I cannot find a straight way to accomplish this, I assume that it's because React's guidelines that naturally prescribe to use ref instead. 不管我到底做了什么,我都找不到直接的方法来实现这一点,我认为这是因为React的指南自然规定使用ref来代替。

How would I use document.getElementById() or anything similar to insert the following sample HTML block at the place of a certain div: 我将如何使用document.getElementById()或类似的东西在特定div位置插入以下示例HTML块:

<div>
    <div class='yellow'>YELLOW</div>
    <div class='green'>GREEN</div>
    <div class='blue'>BLUE</div>
</div>

Assign an id to the top level element of the html react renders. 为html react渲染的顶级元素分配一个ID。 It will still include the id attribute and thus can still be referenced with document.getElementById 它仍将包含id属性,因此仍可以使用document.getElementById进行引用

<div id="toReplace">
    <div className="yellow">YELLOW</div>
    <div className="blue">blue</div>
    <div className="red">red</div>
</div>

componentDidMount() { //or wherever
    document.getElementById('toReplace').append('more html');
}
const str = "<div><div class='yellow'>YELLOW</div><div class='yellow'>GREEN</div><div class='yellow'>BLUE</div></div>"
document.getElementById('toReplace').innerHTML = "";
document.getElementById('toReplace').insertAdjacentHTML( 'beforeend', str );

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

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