React.js粘性导航无法正常工作

vtj*_*205 3 javascript reactjs

我是React.js的新手.我正试图让左侧导航系统坚持滚动.由于某种原因,下面的代码滚动时导致以下错误:

未捕获的TypeError:this.setState不是函数

任何帮助都会很棒!谢谢

class Sticky extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      scrollingLock: false
    };
}

componentDidMount(){
    window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
}

handleScroll() {

  if (window.scrollY > 100) {
    console.log("should lock");
    this.setState({
      scrollingLock: true
    });
  } else if (window.scrollY < 100) {
    console.log("not locked" );
    this.setState({
      scrollingLock: false
    });
  }

}

render() {

    return (
            <div style={{ width: "100%", position: this.state.scrollingLock ? "fixed" : "relative"}}>
                    {this.props.children}
            </div>
          )
            }
   }

export default Sticky;
Run Code Online (Sandbox Code Playgroud)

The*_*son 9

此代码应该适合您.

class Sticky extends React.Component {
constructor(props) {
    super(props);
    this.state = {
      scrollingLock: false
    };
    // example how to bind object in React ES6
    this.handleScroll = this.handleScroll.bind(this)
}

componentDidMount(){
    window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
}

handleScroll() {

  if (window.scrollY > 100) {
    console.log("should lock");
    this.setState({
      scrollingLock: true
    });
  } else if (window.scrollY < 100) {
    console.log("not locked" );
    this.setState({
      scrollingLock: false
    });
  }

}

render() {

    return (
            <div style={{ width: "100%", position: this.state.scrollingLock ? "fixed" : "relative"}}>
                    {this.props.children}
            </div>
          )
            }
   }

 React.render(<Sticky/> , document.body)
Run Code Online (Sandbox Code Playgroud)

这里还有一篇关于ES6 React Code中绑定的好文章.

我希望它会对你有所帮助.

谢谢