猿问

更改工具栏背景颜色并在身体倾斜时做出反应

我正在尝试将工具栏背景颜色更改为#fff正文滚动时的颜色。否则它将是transparent.


这是示例工具栏组件:


export default class ToolBar extends React.Component {

  constructor(props){

    super(props)

    this.state = {

      scrolled:false

    }

  }

  render() {

    const { children, className,scrolled, ...other } = this.props

    return (

      <nav style={{backgroundColor:this.state.scrolled?'#fff':'transparent'}}>

        {children}

      </nav>

    )

  }

}

我们如何通过反应来做到这一点?


Helenr
浏览 135回答 1
1回答

狐的传说

只需将事件侦听器添加到窗口对象即可。componentDidMount() {&nbsp; &nbsp;window.addEventListener('scroll', this.checkScroll);}checkScroll = () => {&nbsp; &nbsp;this.setState({ scrolled: window.scrollY > 0 });};注意:您可能还需要一些去抖动以避免快速和多个设置状态。并记住在组件销毁时断开侦听器。componentWillUnmount() {&nbsp; &nbsp;window.removeEventListener('scroll', this.checkScroll);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答