如何在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>
);
}
你需要在构造函数中将'this'绑定到thorttle。
constructor() {
super();
this.throttle = this.throttle.bind(this);
this.getElementPosition = this.getElementPosition.bind(this)
}
throttle() {
_.throttle(this.getElementPosition, 100)
}
试试这个,每个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
}
注意doThrottle
和getPosition
上的箭头函数将其转换为组件中的隐式bind(this)
。最初的问题在于你自己的油门方法,其中this
没有绑定到你的组件。