You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native实现ScrollView单个子项占满全屏 单次滚动仅展示一个个人资料

React Native ScrollView 单屏占比滚动实现方案

核心修改点

  • 补充获取屏幕高度,给每个资料卡片设置全屏高度
  • 给ScrollView开启分页滚动属性,保证每次滚动只切换一个卡片
  • 给ScrollView本身添加flex:1样式,保证它能占满父容器的可用空间

修改后的组件代码

import { Dimensions } from 'react-native';

const ProfileVerticalScroll = ({
  active = 0,
  setActive,
  profileData,
  scrollViewRef,
}: Props) => {
  // 滚动结束后更新当前激活的索引
  const handleScrollEnd = (e) => {
    const offsetY = e.nativeEvent.contentOffset.y;
    const pageHeight = Dimensions.get('window').height;
    const currentIndex = Math.round(offsetY / pageHeight);
    setActive(currentIndex);
  };

  return (
    <ScrollView 
      style={styles.scrollView} 
      ref={scrollViewRef}
      pagingEnabled={true}
      showsVerticalScrollIndicator={false}
      onMomentumScrollEnd={handleScrollEnd}
    >
      {profileData.map((el, index) => {
        return (
          {/* 实际项目建议用数据唯一id代替index作为key */}
          <View key={index} style={styles.profile}>
            <View style={styles.profileHeadings}>
              <Text>{el.name} </Text>
              <Text>{el.profession}</Text>
            </View>
            <View style={styles.abouteMe}>
              <Text> About Me</Text>
              <Text>{el.info}</Text>
            </View>
          </View>
        );
      })}
    </ScrollView>
  );
};

export default ProfileVerticalScroll;

修改后的样式代码

import { StyleSheet, Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');
export default StyleSheet.create({
  scrollView: {
    flex: 1,
  },
  profile: {
    height: height,
    flexDirection: 'column',
    alignItems: 'center',
    width: width,
    paddingHorizontal: width * 0.05,
    // 如果页面有顶部导航栏/状态栏,可把上面的height替换为 height: height - 导航栏高度 - 状态栏高度
  },
  profileHeadings: {},
  abouteMe: {},
});

补充说明

  • pagingEnabled 开启后ScrollView会自动按自身尺寸分页,滚动结束时会停在整页位置,不会出现两个卡片同时展示的情况
  • React Native中flex布局默认就是flexDirection: column,display: 'flex'也可以省略不写

内容的提问来源于stack exchange,提问作者Alwaysblue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:36:03