javascript - 在滚动时 react 改变 NavBar 的样式

标签 javascript css reactjs

我正在这里练习一些 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>
    )
  }
}

最佳答案

nonebackgroundColor 无效。

请尝试 const top = {backgroundColor: 'transparent'}

关于javascript - 在滚动时 react 改变 NavBar 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59259027/

相关文章:

javascript - Z-index 似乎没有任何改变

javascript - 为什么 Next.js 自定义服务器禁用自动静态优化?

html - 仅限 iPad 的 CSS + 桌面 CSS 冲突?

html - 将 div 附加到相对于背景的精确位置(大小为 : cover)

ReactJS:使用 useState 管理多个复选框输入

reactjs - React Hook "useEffect"无法在回调内调用发生错误

javascript - 如何在使用javascript输入时将输入字段文本的第一个字母大写?

javascript - Ajax 发送重复的 header

html - css:将一个 div 附加到居中的 div

reactjs - 使用三个 JS 和 React JS 加载 GLTF 模型