【发布时间】:2018-02-03 19:39:18
【问题描述】:
问你这个问题我有点不好意思,因为我相信解决这个问题很简单,而且是基本的。但我仍然坚持这一点。
我想改变我的风格,例如。当 onscroll 事件触发时,我的 div 的 backgroundColor,但这似乎不起作用。 在尝试像这样设置它时 backgroundColor:this.state.backgroundColor, 出现错误:Cannot read property 'state' of undefined
提前致谢!
这是我的代码:
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;
【问题讨论】: