【问题标题】:TypeError when Dynamically Changing CSS in ReactJs Component在 ReactJs 组件中动态更改 CSS 时出现 TypeError
【发布时间】: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


【解决方案1】:

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

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

这一行将在body标签中添加一个样式属性:

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

【讨论】:

    【解决方案2】:

    如果你只是想改变 body 元素的背景颜色,你可以这样做document.body.style.backgroundColor = 'red'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2021-08-17
      • 1970-01-01
      • 2021-01-24
      • 2020-06-06
      • 2021-06-08
      相关资源
      最近更新 更多