在 React 中使用 setState 更改样式属性

Mur*_*ami 10 css reactjs

我有点不好意思问你这个问题,因为我相信解决这个问题很简单,而且很基本。但我仍然坚持这一点。

我想改变我的风格,例如。当 onscroll 事件触发时,我的 div 的 backgroundColor ,但这似乎不起作用。在尝试将其设置为这样的 backgroundColor:this.state.backgroundColor 时,出现错误:无法读取未定义的属性“状态”

提前致谢!

这是我的代码:

import React, { Component } from 'react';

class Header extends Component {
    constructor(props) {
        super(props);
        this.state = {
            backgroundColor: 'black',
        };
    }

    componentDidMount() {
        const headerElement = this.refs.header;
        const sticky = headerElement.offsetTop;
        window.addEventListener('scroll', () => this.handleScroll(sticky)); 
    }

    handleScroll(sticky) {
        if (window.pageYOffset >= sticky) {
            this.setState({
                backgroundColor: 'yellow'
            });
        }
    }

    render() {
        const { containerStyle } = styles;
        return (
            <header style={containerStyle} ref='header'> {this.props.text} </header>
        );
    }
}

const styles = {
    containerStyle: {
        backgroundColor: this.state.backgroundColor,
    }
};

export default Header;
Run Code Online (Sandbox Code Playgroud)

Bar*_*Gee 11

不必羞于提问,我还没有遇到过一个还不是学生的开发人员,包括我自己。:)

您的styles变量超出范围。您需要将其移动到您的render()函数中。

在这里查看工作代码:https : //codesandbox.io/s/3rynvvn18m?module=%2Fheader.js