我将在现有网站中渲染一个 React 组件,根元素的示例可能是:
<div id="root"></div>
我想做的是,首先访问根元素内的任何 html:
<div id="root">Hello world</div>
文档 seems to indicate你可以按照以下方式做一些事情:
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.
我尝试使用 refs 进行访问,但无法访问这些子 DOM 元素,有谁知道我如何实现此目的?
<div id="root" ref="root">Hello world</div>
最佳答案
不幸的是,这在 ReactDOM 中无法直接实现。
<div id="root">
中的“Hello world”字符串被视为容器节点的子节点,因此被覆盖。
相反,您需要获取 .innerHTML
来自div
ID 为root
之前 ReactDOM 的 render()
方法被调用。然后你就可以用它做任何你想做的事:
let root = document.getElementById("root");
let existingContent = root.innerHTML;
ReactDOM.render(yourReactComponent, root);
console.log(existingContent); // Do whatever you need to do with this
关于javascript - 使用 React 渲染时如何访问现有的 dom 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352977/