首页 > 解决方案 > 未调用 React-Native onScroll 事件

问题描述

我正在尝试创建一个分页/无限滚动组件,但该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没有。

标签: reactjsreact-nativescrollview

解决方案


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

在构造函数中绑定handleOnScroll

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

或者

改成箭头函数

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

推荐阅读