javascript - 如何访问 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 未定义
如何使这项工作?任何提示都会很棒,谢谢
解决方案
尝试将您的变量声明从文档更改为其他内容,例如
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})
}
推荐阅读
- django - 尝试了很多关于 Django 迁移问题的方法,但我仍然无法修复此错误?
- python - 在 Plot Python 中获取峰值
- python - Python dendrogram 必须有 ak 使得 (k \choose 2)=n)
- python - TypeError:不支持的操作数类型 %:'tuple' 和 'int'
- bash - BASH - 通过文件中的每一行使用 IF 循环(for)
- javascript - 如何使用 html 和 js 在 foreach 循环中为单个按钮创建动态 ID
- c# - 如何在 linq 的动态列表中查找重复项?
- android - 如何在 Android 的 SQLite 数据库的第二个表中插入第一个表 ID?
- google-bigquery - 外部表定义中的 skipLeadingRows=1
- ios - 订阅到期时,Apple 订阅回调不会通知我们(沙盒)