滚动更改NavBar的样式

问题描述 投票:2回答:1

我正在这里练习一些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>
    )
  }
}
javascript css reactjs
1个回答
1
投票

[nonebackgroundColor无效。

改为尝试const top = {backgroundColor: 'transparent'}

© www.soinside.com 2019 - 2024. All rights reserved.