如何在ReactJS中访问根元素?

时间:2019-02-14 13:21:55

标签: javascript reactjs

我正在尝试修改:root{}中包含的CSS变量。我尝试了两种选择:

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未定义

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

1 个答案:

答案 0 :(得分:3)

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

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})
}