通过id添加滚动侦听器

时间:2019-12-26 09:06:28

标签: reactjs dom listener

嗨,我无法通过ID添加滚动侦听器,它可以与WINDOW一起使用,但不能在自定义滚动元素中使用。 这是我的代码:

componentDidMount() {
    const scrollPanel = document.getElementById('scrollPanel');
    scrollPanel.addEventListener('scroll', this.listenToScroll);
  }

componentWillUnmount() {
    const scrollPanel = document.getElementById('scrollPanel');
    scrollPanel.removeEventListener('scroll', this.listenToScroll);
  }

listenToScroll = () => {
    const { position } = this.state;
    const scrollPanel = document.getElementById('scrollPanel');
    const winScroll = scrollPanel.scrollTop;
    const height =
         scrollPanel.scrollHeight -
         scrollPanel.clientHeight;

    const scrolled = winScroll / height;
    console.log('scrolled', scrolled);
    this.setState({
      position: scrolled,
    });

当我尝试检查一些值时,它永远不会改变

1 个答案:

答案 0 :(得分:0)

该元素内必须有一个事件处理程序,该事件处理程序会创建滚动元素: 根据您的情况,将componentDidMount()更改为以下内容:

componentDidMount() {
        document.addEventListener(
            "scroll",
            this.listenToScroll,
            true // Capture event
        );
    }
    listenToScroll = () => {
        //Your custom code
        alert("click triggered");
    };

我尝试过并且有效

您可能想检查一下这个答案,我从哪里得到了参考: https://stackoverflow.com/a/30475606