如何在React中的滚动事件上绑定到_.throttle

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

如何在React中调节一个调用滚动的函数,该函数使用如下所示的bind?

this.getElementPosition = this.getElementPosition.bind(this);

到目前为止我所拥有的是以下内容,但它让我回到了TypeError: Cannot read property 'bind' of undefined

throttle() {
  _.throttle((this.getElementPosition = this.getElementPosition.bind(this)), 100)
}

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

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

getElementPosition() {
  var rect = this.elementPosition.getBoundingClientRect();

  if ((rect.top > 0) && (rect.top < (window.innerHeight * 0.75))) {
    this.elementPosition.setAttribute("data-position","in-viewport");
  } else if (rect.top > window.innerHeight) {
    this.elementPosition.setAttribute("data-position","below-viewport");
  } else if (rect.bottom < 0) {
    this.elementPosition.setAttribute("data-position","above-viewport");
  }
}

render() {
  return (
    <div ref={(element) => { this.elementPosition = element; }} data-position="below-viewport">
    </div>
  );
}
reactjs
2个回答
1
投票

你需要在构造函数中将'this'绑定到thorttle。

constructor() {
  super();
  this.throttle = this.throttle.bind(this);
  this.getElementPosition = this.getElementPosition.bind(this)
}

throttle() {
 _.throttle(this.getElementPosition, 100)
}

0
投票

试试这个,每个lodash docs https://lodash.com/docs/4.17.4#throttle

componentDidMount() {
  window.addEventListener('scroll', _.throttle(this.doThrottle, 100))
}

doThrottle = () => {
  this.getElementPosition = this.getPosition()
}

getPosition = () => {
  // stuff
}

注意doThrottlegetPosition上的箭头函数将其转换为组件中的隐式bind(this)。最初的问题在于你自己的油门方法,其中this没有绑定到你的组件。

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