当前位置: 代码迷 >> JavaScript >> 如何在ReactJS中访问根元素?
  详细解决方案

如何在ReactJS中访问根元素?

热度:105   发布时间:2023-06-13 12:25:20.0

我正在尝试修改: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未定义

如何运作? 任何提示都会很棒,谢谢

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

let doc = document.documentElement;

我认为您的声明已被吊起(请参阅: : ),所以当您实际上日志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})
}