我正在这里练习一些React。我希望我的NavBar
超过我已经完成的某个滚动点的backgroundColor
,但是当我滚动回到顶部时,backgroundColor
不会变回无。我在这里先向您的帮助表示感谢。
const top = {backgroundColor: 'none'}
const scrolled = {backgroundColor: 'rgba(0,0,0,0.4)'}
class NavBar extends React.Component {
constructor() {
super();
this.state = {style: top};
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = e => {
if (window.scrollY < 200) {
this.setState({style: top})
} else if (window.scrollY > 200) {
this.setState({style: scrolled})
}
}
render() {
return (
<div className='navBarContainer'>
<nav className = 'navBar' onScroll={this.handleScroll} style={this.state.style}>
<a className='navItem home' href='#'>SAINT<br />BARLEY<br />ROASTING</a>
<a className='navItem shop' href='#'>shop</a>
<a className='navItem blog' href='#'>blog</a>
<a className='navItem bio' href='#'>bio</a>
</nav>
</div>
)
}
}
[none
对backgroundColor
无效。
改为尝试const top = {backgroundColor: 'transparent'}
。