为什么在React中呈现元素的函数中DOM方法的行为是不确定的



我只是尝试使用文档方法,如getElementsByClassNamegetElementsByTagNamegetElementById,并合并输出。然而奇怪的是,只有getElementById不工作,它记录了null。我尝试过className与App和TagName h1配合使用,效果非常好。有人能阐明这一点吗?这是代码沙盒[https://codesandbox.io/s/813mnx1vq2]。

以下是我正在渲染的App的代码,

function App() {
{ console.log(document.getElementById('heading1')) }
/*
{ console.log(document.getElementsByTagName("h1")) }
// Output: HtmlCollection array which contains element with id=heading1
*/
/*
{ console.log(document.getElementsByClassName("App")) }
// Output: HtmlCollection array which contains div.App element
*/
return (
<div  className="App">
<h1 id="heading1">Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

PS编辑:NodeList什么时候是活动的,什么时候是静态的。感谢乔纳斯。

从这些方法返回的数据结构有两种类型,一种是NodeList,另一种是单个节点。NodeList的特殊之处在于它们是活动的,这意味着如果一个节点被添加到DOM中,它也会被添加到NodeList中。在控制台中,您可以看到所记录内容的实时版本,因此您还可以使用getElementsByTagName看到尚未在DOM中的元素,而使用getElementByID则没有结果。

尽管如此,在使用React时,您根本不应该使用它们。

调用getElementById时,DOM节点不可用。

一个简单的解决方案是将组件转换为类组件,并使用componentDidMount生命周期方法。

class App extends React.Component {
componentDidMount() {
console.log(document.getElementById('heading1'))
}
render() {
return (
<div  className="App">
<h1 id="heading1">Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
}

如果你严格想要功能组件,有一个库可以访问功能组件中的生命周期方法,称为反应纯生命周期

最新更新