未调用React-Native onScroll事件

时间:2018-10-18 20:48:12

标签: reactjs react-native scrollview

我正在尝试创建一个分页/无限滚动组件,但从未触发onScroll事件。

有人知道我在做什么错吗?

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ScrollView } from 'react-native';

class PaginatedScrollView extends Component {
    static propTypes = {
        paginationSize: PropTypes.number,
        data: PropTypes.array.isRequired,
        renderItem: PropTypes.func.isRequired
    }

    handleOnScroll (event) {
        console.log(event.nativeEvent.contentOffset.y);
    }

    render () {
        const {
            data,
            renderItem,
            paginationSize
        } = this.props;

        return (
            <ScrollView
                onScroll={e => this.handleOnScroll(e)}
                onContentSizeChange={console.log}
            >
                {data
                    .slice(1, paginationSize)
                    .map(renderItem)
                }

            </ScrollView>
        );
    }
}

export default PaginatedScrollView;

似乎正在调用onContentSizeChange,但没有调用onScroll

2 个答案:

答案 0 :(得分:1)

您需要在构造函数中绑定handleOnScroll函数或将其更改为箭头函数

在构造函数中绑定handleOnScroll

  constructor(props){
       super(props);
       this.handleOnScroll = this.handleOnScroll.bind(this);
  }

OR

将其更改为箭头功能

 handleOnScroll = event => {
    console.log(event.nativeEvent.contentOffset.y);
}

答案 1 :(得分:0)

虽然确实如此,但是您可能需要绑定函数(如果要在事件处理程序中使用this),这不是导致您看不到onScroll回调的原因。

使用ScrollView onScroll事件处理程序时,您还需要通过传递最小值为16的附加scrollEventThrottle道具来指定获取滚动信息的频率(以每16毫秒获取一次事件,这相当于以60fps的每一帧获取一次),否则,您只会得到第一个事件。

关于您要做什么的其他一些注意事项:

  • 您可能希望将onScroll的值传递给处理程序,而不是每次都创建一个匿名函数,例如:onScroll={this.handleOnScroll}
  • 要实现无限滚动,最好使用FlatList。因为React Native DocumentationScrollViews对于少量物品比较好:
  

ScrollView最适合显示少量有限大小的东西。即使当前未在屏幕上显示,也将呈现ScrollView的所有元素和视图。如果一长串的项目超出了屏幕显示的容量,则应改用FlatList