首页 > 解决方案 > 如何访问 ReactJS 中的根元素?

问题描述

我正在尝试修改包含在:root{}. 我尝试了两种选择:

componentDidMount(){ 

A) 

if (typeof window !== "undefined" ) {
    console.log("typeof window: ",typeof document)
    let document = document.documentElement;
    this.setState({document})
}    

B)

if (typeof document !== "undefined" ) {
    console.log("typeof document: ",typeof document)
    let document = document.documentElement;
    this.setState({document})
 }    
}

他们都返回:

_document 未定义

如何使这项工作?任何提示都会很棒,谢谢

标签: javascriptreactjs

解决方案


尝试将您的变量声明从文档更改为其他内容,例如

let doc = document.documentElement;

我认为你的声明被提升了(见:https ://medium.freecodecamp.org/what-is-variable-hoisting-differentiating-between-var-let-and-const-in-es6-f1a70bb43d )所以当你真的记录typeof document它实际上是指您的let document =而不是全局文档

您的代码实际上是什么样的:

if (typeof window !== "undefined" ) {
    let document;
    console.log("typeof window: ",typeof document) // when this looks for document it is going to look in the current scope which is the one defined above, which is undefined at the moment
    document = document.documentElement;
    this.setState({document})
}   

推荐阅读