javascript - React.js 粘性导航不起作用

标签 javascript reactjs

我是 React.js 的新手。我试图让左侧导航保持滚动。出于某种原因,当我滚动时,下面的代码会导致以下错误:

未捕获的类型错误: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;

最佳答案

此代码应该适合您。

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)

还有 here是一篇关于 ES6 React 代码中绑定(bind)的好文章。

希望对您有所帮助。

谢谢

关于javascript - React.js 粘性导航不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33555021/

相关文章:

javascript - jQuery 函数显示带有显示 : none 的 div

javascript - 在 WinJS 中将文件下载到文件系统

reactjs - 从 React Components 生成 PDF 文件

reactjs - 草稿.js : how to preserve paragraph breaks when pasting content?

javascript - 在回调中使用重定向来响应登录

javascript - 如何在对象数组中找到具有最长字符长度的对象键

javascript - Netlify 未检测到 GatsbyJS 表单

javascript - this.setState 和 this.state.child 使用

javascript - 单击调整div的大小

javascript - 3 列轮播 slider 黑白居中图像