如何在react.js中的scroll事件上调用我的函数?

时间:2018-04-03 09:41:56

标签: reactjs

大家好我有一个问题我正在使用reactjs我创建了一个名为Storymap的类,然后我创建了一个同时滚动2个div的函数

例如

,滚动在bot div'第二个div'

  Scrolling = () => {
    var isSyncingLeftScroll = false,
      isSyncingRightScroll = false,
      leftDiv = document.getElementById('top'),
      rightDiv = document.getElementById('bot');

    leftDiv.onscroll = () => {
      if (!isSyncingLeftScroll) {
        isSyncingRightScroll = true;
        rightDiv.scrollLeft = this.scrollLeft;
      }
      isSyncingLeftScroll = false;
    };

    rightDiv.onscroll = () => {
      if (!isSyncingRightScroll) {
        isSyncingLeftScroll = true;
        leftDiv.scrollLeft = this.scrollLeft;
      }
      isSyncingRightScroll = false;
    };
  }

我称之为

<div className="divdeux" id="bot" onScroll={this.Scrolling}> 

但它不起作用!为了我 感谢任何需要时间审阅并提供反馈的人。

1 个答案:

答案 0 :(得分:1)

这样的事情应该可以胜任:

  componentDidMount() {
    this.refContainer.addEventListener('scroll', this.onScroll);
  }

  componentWillUnmount() {
    this.refContainer.removeEventListener('scroll', this.onScroll);
  }

  onScroll = () => {
    var isSyncingLeftScroll = false,
      isSyncingRightScroll = false,
      leftDiv = document.getElementById('top'),
      rightDiv = document.getElementById('bot');

    leftDiv.onscroll = () => {
      if (!isSyncingLeftScroll) {
        isSyncingRightScroll = true;
        rightDiv.scrollLeft = this.scrollLeft;
      }
      isSyncingLeftScroll = false;
    };

    rightDiv.onscroll = () => {
      if (!isSyncingRightScroll) {
        isSyncingLeftScroll = true;
        leftDiv.scrollLeft = this.scrollLeft;
      }
      isSyncingRightScroll = false;
    };
  }

  ...

  render() {
    return (
      <div
        className="divdeux"
        id="bot"
        ref={ref => {
          this.refContainer = ref;
        }}
      >
        {/* whatever you have in the div */}
      </div>
    );
  }