简体   繁体   中英

How can I access existing dom elements when using react render?

I will rendering a React component in to an existing website, an example of the root element might be:

<div id="root"></div>

What I would like to do is, access any html inside the root element to begin with for example:

<div id="root">Hello world</div>

The documentation seems to indicate you can do something along these lines:

ReactDOM.render() does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.

I have tried to access using refs but I can't access these child DOM elements, does anyone know how I can achieve this?

<div id="root" ref="root">Hello world</div>

Unfortunately this isn't possible in ReactDOM directly .

The "Hello world" string in your <div id="root"> is treated as a child of the container node, and is therefore overwritten.

Instead, you'll need to get the .innerHTML from the div with the ID of root before ReactDOM's render() method is called. You can then do whatever you want with this afterwards:

let root = document.getElementById("root");
let existingContent = root.innerHTML;
ReactDOM.render(yourReactComponent, root);
console.log(existingContent); // Do whatever you need to do with this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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