通过id添加滚动侦听器

问题描述 投票:0回答:1

[嗨,我无法通过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,
    });

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

reactjs dom listener
1个回答
0
投票

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

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

我尝试过并且有效

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

© www.soinside.com 2019 - 2024. All rights reserved.