我正在这里练习一些 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'}
。
关于javascript - 在滚动时 react 改变 NavBar 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259027/