Javascript 如何访问ReactJS中的根元素?
我试图修改Javascript 如何访问ReactJS中的根元素?,javascript,reactjs,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 docu
: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})
}
}
他们都返回:
_文档未定义
这是怎么做到的?
任何暗示都很好,
谢谢尝试将变量声明从文档更改为其他内容,例如
let doc = document.documentElement;
我认为您的声明正在被搁置(请参阅:),因此当您实际记录文档的类型时,它实际上指的是您的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})
}
尝试将变量声明从文档更改为其他内容,例如
let doc = document.documentElement;
我认为您的声明正在被搁置(请参阅:),因此当您实际记录文档的类型时,它实际上指的是您的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})
}
这个代码放在哪里?它被执行了吗?。代码本身是好的,但问题是它在组件生命周期的哪一点上是活跃的谢谢你的回答:),他们生活在componentDidMount()中,在我看来,当组件被挂载时,它应该意味着DOM在这里,因此窗口也在这里?这段代码放在哪里?它被执行了吗?。代码本身是好的,但问题是它在组件生命周期的哪一点上是活跃的谢谢你的回答:),它们在componentDidMount()中,在我看来,当组件被装载时,它应该意味着DOM在这里,因此窗口也在这里?