gpt4 book ai didi

javascript - 在 ReactJs 组件中动态更改 CSS 时出现 TypeError

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:46 25 4
gpt4 key购买 nike

我试图在按下键盘上的向上箭头时动态更改我的 ReactJs 网络应用程序的背景颜色。但是,在运行此代码时,我收到以下错误消息:

Uncaught TypeError: Cannot read property 'setAttribute' of null

放置这段代码的组件有一个呈现整个应用程序的父组件。

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 中动态更改背景颜色的更好方法的任何建议?

谢谢!

最佳答案

background-color 不是 html 属性,是 css 属性,您可以更改样式属性,然后将 background-color 设置为样式属性的值,对于示例:

document.getElementById("body").setAttribute("style", "background-color:#000000");

这一行将向 body 标签添加样式属性:

<body style="background-color: #00000">

关于javascript - 在 ReactJs 组件中动态更改 CSS 时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39432883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com