【问题标题】:React-Native onScroll Event is Not Being Called未调用 React-Native onScroll 事件
【发布时间】:2018-10-18 20:48:12
【问题描述】:

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

【问题讨论】:

    标签: reactjs react-native scrollview


    【解决方案1】:

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

    在构造函数中绑定handleOnScroll

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

    改成箭头函数

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

    【讨论】:

    • 成功!。谢谢。虽然我原以为调用方法 (onScroll={e =&gt; this.handleOnScroll(e)}) 会处理这个问题。
    • 不客气。不,您需要执行我在回答中建议的操作。请记住,如果你想手动绑定函数,那么你应该总是像我一样只在构造函数中绑定函数。永远不要绑定组件中的其他任何地方。
    • 查看本帖详细了解正则函数和箭头函数stackoverflow.com/questions/52031147/…
    【解决方案2】:

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

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

    您想要做的一些其他注意事项:

    • 您可能希望将处理程序作为onScroll 属性的值传递,而不是每次都创建一个匿名函数,例如:onScroll={this.handleOnScroll}
    • 要实现无限滚动,最好使用FlatList。因为React Native Documentation 表示ScrollViews 更适合少量物品:

    ScrollView 最适合呈现有限大小的少量事物。 ScrollView 的所有元素和视图都会被渲染,即使它们当前没有显示在屏幕上。如果你有一个长长的列表,其中的项目超出了屏幕的显示范围,你应该使用 FlatList 来代替

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      相关资源
      最近更新 更多