滚动事件后的React.js调用函数 [英] React.js Call function after scroll event

查看:92
本文介绍了滚动事件后的React.js调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个React组件,该组件应该在窗口滚动事件时调用该函数.

I have built a React component which is suppose to call the function on window scroll event.

当用户滚动到滚动高度的90%时,我想调用函数"getCards('default')".

I would like to call the function, "getCards('default'), when the user scroll to 90% of the scroll height.

该组件的外观如下所示:

The component looks as shown in below:

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');
  }

有人可以帮助我实现这一目标吗?

Could anyone help me achieve this?

谢谢.

推荐答案

您必须使用组件,请参考以下代码:

You have to work with your component, please refer to this code:

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(...);
    } 
  }

滚动事件必须放置在组件内部,并使用onScroll evt绑定.处理程序将检查已用屏幕尺寸的百分比,如果达到下限限制,则将加载其他元素.

The scroll event must be placed inside your component and binded using onScroll evt. The handler will check for percentage of used screen size and will load others elements if the lower bound limit is reached.

我希望这会有所帮助:)

I hope this can help :)

这篇关于滚动事件后的React.js调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆