【发布时间】:2019-03-05 06:12:51
【问题描述】:
我有一个有状态的组件,它有一个像这样的滚动事件监听器
import React, { Component } from 'react'
import { withRouter } from 'react-router'
import AppDetailPageUI from './AppDetailPageUI.js'
class AppDetailPageSF extends Component {
constructor(props) {
super(props);
this.state = {
scrolledDown:false,
};
this.handleScroll = this.handleScroll.bind(this);
}
render() {
return (
<AppDetailPageUI
scrolledDown={this.state.scrolledDown}
/>
);
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
if (window.scrollY === 0 && this.state.scrolledDown === true) {
this.setState({scrolledDown: false});
}
else if (window.scrollY !== 0 && this.state.scrolledDown !== true) {
this.setState({scrolledDown: true});
}
}
}
export default withRouter(AppDetailPageSF)
这工作得很好。但是我想在许多有状态的组件中使用 handleScroll 方法,并且在每个组件中包含相同的方法并不是一个好习惯。
所以这就是我尝试的方法,我创建了另一个 HandleScrollUtil 函数,类似这样
const HandleScrollUtil = {
handleScroll: function(component) {
if (window.scrollY === 0 && component.state.scrolledDown === true) {
component.setState({scrolledDown: false});
}
else if (window.scrollY !== 0 && component.state.scrolledDown !== true) {
component.setState({scrolledDown: true});
}
}
}
export default HandleScrollUtil
然后我尝试通过传递这个引用来调用这个方法
componentDidMount() {
window.addEventListener('scroll', HandleScrollUtil.handleScroll(this));
}
componentWillUnmount() {
window.removeEventListener('scroll', HandleScrollUtil.handleScroll(this));
}
但它现在似乎不起作用。
【问题讨论】:
标签: javascript reactjs components