我已经构建了一个React组件,该组件应该在窗口滚动事件上调用该函数。
当用户滚动到滚动高度的90%时,我想调用函数“getCards('default')”。
该组件如下图所示:
class Home extends React.Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount() {
// test
this.props.getCards('default');
window.addEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
console.log('scroll event');
}
谁能帮助我实现这一目标?
谢谢。
最佳答案
您必须使用组件,请引用以下代码:
class Home extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
// test
this.props.getCards('default');
}
render() {
return (<div onScroll={this.handleScroll}>...</div>)
}
handleScroll(event) {
var heightBound = window.height * 0.8
if (heightBound > window.scrollY) {
// Probably you want to load new cards?
this.props.getCards(...);
}
}
scroll事件必须放置在组件内部,并使用onScroll evt绑定(bind)。处理程序将检查已用屏幕尺寸的百分比,如果达到下限限制,则将加载其他元素。
我希望这可以帮助:)