【发布时间】:2016-09-11 04:34:59
【问题描述】:
我试图在按下键盘上的向上箭头时动态更改我的 ReactJs Web 应用程序的背景颜色。但是,在运行此代码时,我收到以下错误消息:
未捕获的类型错误:无法读取 null 的属性“setAttribute”
这段代码所在的组件有一个渲染整个应用程序的父级。
handleKeyDownEvent(event) {
if (event.keyCode == 38) {
event.preventDefault();
/*if up key or swipe up*/
if (this.state.isInverted == false) {
document.getElementById("body").setAttribute("background-color", "#000000");
this.setState({ isInverted: true });
}
else {
document.getElementById("body").setAttribute("background-color", "#FFFFFF");
this.setState({ isInverted: false });
}
}
}
我该如何解决这个问题?关于在 React 中动态更改背景颜色的更好方法的任何建议?
谢谢!
【问题讨论】:
-
你能显示你的标记吗? id 为
body的元素似乎不存在。
标签: javascript css reactjs