React native确定用户是否在屏幕顶部

React native determine if user is at the top of the screen

本文关键字:屏幕 顶部 是否 用户 native React      更新时间:2023-09-26

在web中的javascript中,我会这样做,以确定用户是否在可滚动页面/文档的顶部:

$(document).scroll(function() { 
   if($(window).scrollTop() === 0) {
     //do stuff
   }
});

在React Native中是否有类似的东西可以帮助我确定用户是否在屏幕的顶部?

使用ScrollView,您可以这样做:

_handleScroll(event) {
    if(event.nativeEvent.contentOffset.y <= 0) {
        console.log('top!');
    }
}
render() {
    return (
        <View style={styles.container}>
            <ScrollView 
                onScroll={this._handleScroll}     
                onScrollAnimationEnd={this._handleScroll} 
                style={{flex: 1}}>
                    <View style={[styles.child, {backgroundColor: 'red'}]} />
                    <View style={[styles.child, {backgroundColor: 'orange'}]} />
                    <View style={[styles.child, {backgroundColor: 'green'}]} />
            </ScrollView>
        </View>
    );
}
var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
    },
    child: {
        flex: 1,
        height: 400,
    }
});

希望有帮助!

ScrollView组件有onScroll方法。pageX和pageY属性 evt nativeEvent contentOffset x y

handleScroll(event) {
 console.log(event.nativeEvent.contentOffset.y)
},
<ScrollView onScroll={this.handleScroll}/>