React Native 基础组件详解<二>

一、FlatList组件

1)data:渲染数据源,数组

2)renderItem:渲染ui函数

3)keyExtractor:生成唯一key的函数

4)contentContainerStyle:包裹内容的容器的样式

5)showsVerticalScrollIndicator:滚动时,是否显示纵向滚动条

6)onScroll:滚动回调

7)keyboardDismissMode: 当键盘拉起时,滚动键盘是否消失 on-drag(消失)

8)keyboardShouldPersistTaps:当键盘拉起时,点击滚动区域键盘是否消失 never(消失)/always(不消失)/handled(消失)

!!!never和handled的区别:**键盘和Button同时存在的情况下:

never:点击按钮,键盘收起,但是Button的onPress没有直接执行

handled:点击按钮,键盘不会收起,Button的onPress直接执行,点击滚动区域的非按钮部分,键盘收起

9)horizontal:是否横向

10)ListHeaderComponent:列表头部组件

11)ListFooterComponent:列表尾部组件

12)ItemSeparatorComponent:每个item的分隔组件

13)initialNumToRender:初始化第一屏渲染几个

14)inverted:是否顺序反向渲染

15)onViewableItemsChanged:获取可视区域的item列表

16)滚动到指定index的item: ref.scrollToIndex({index: xx, ...})

17)滚动到指定的item:ref.scrollToItem({item: xx, ...}) ---- 不推荐

18)滚动到指定的像素:ref.scrollToOffset({offset: xx})

18)滚动到底部:ref.scrollToEnd()

javascript 复制代码
useEffect(() => {
   setTimeout(() => {
       // flatListRef.current.scrollToIndex({
       //     index: 10,
       //     viewPosition: 0.5, // index的item滚动到的位置 0-顶部 0.5-中间  1-底部
       //     animated: true,
       // });

       // flatListRef.current.scrollToItem({
       //     item: 5,
       //     viewPosition: 0,
       //     animated: true,
       // });

       // flatListRef.current.scrollToOffset({
       //     offset: 200,
       // });

       flatListRef.current.scrollToEnd({
           animated: true,
       });
   }, 2000);
}, []);

 const renderItem = ({ item, index }) => {
     return (
         <Text style={styles.txt}>{`List item ${item}`}</Text>
     );
 }

return (
// ...
	<FlatList
        ref={flatListRef}
        style={styles.flatlist}
        data={data}
        renderItem={renderItem}
        keyExtractor={(_, index) => `item-${index}`} // (item, index)中的item没有用到但不能删时,可写成---
        contentContainerStyle={styles.containerStyle}
        showsVerticalScrollIndicator={false}
        onScroll={(event) => {
            console.log(event.nativeEvent.contentOffset.y);
        }}
        keyboardDismissMode='on-drag'
        keyboardShouldPersistTaps='handled'
        ListHeaderComponent={
            <View style={styles.header}>
                <Text style={styles.extraTxt}>列表头部</Text>
            </View>
        }
        ListFooterComponent={
            <View style={[styles.header, styles.footer]}>
                <Text style={styles.extraTxt}>列表尾部</Text>
            </View>
        }
        ListEmptyComponent={
            <View style={styles.listEmpty}>
                <Text style={styles.extraTxt}>暂无数据~</Text>
            </View>
        }
        ItemSeparatorComponent={
            <View style={styles.separator} />
        }
        initialNumToRender={15}
        inverted={false}
        // numColumns={2}
        // onViewableItemsChanged={(info) => {
        //     const { viewableItems } = info;
        //     console.log(viewableItems);
        // }}
    />
)

19)ListEmptyComponent:暂无数据时的组件

20)numColumns:一行显示几个item

二、SectionList组件

1)sections:数据源 {data: xx,xx,xx}\[\]

2)renderItem:渲染item函数

3)keyExtractor:生成唯一key函数

4)contentContainerStyle:包裹内容的容器的样式

5)showsVerticalScrollIndicator:滚动时,是否显示纵向滚动条

6)onScroll:滚动回调

7)keyboardDismissMode: 当键盘拉起时,滚动键盘是否消失 on-drag(消失)

8)keyboardShouldPersistTaps:同FlatList组件

9)ListHeaderComponent:列表头部组件

10)ListFooterComponent:列表尾部组件

11)renderSectionHeader:每个section的头部组件

12)ItemSeparatorComponent:item分隔组件

13)stickySectionHeadersEnabled:section头部是否吸顶

14)指定滚动到的位置:ref.scrollToLocation({sectionIndex: xx, itemIndex: xx, ...})

注意:itemIndex

javascript 复制代码
export const SectionData = [
    {type: 'A', data: ['安达', '安宁', '安吉', '安家', '安可', '安庆', '阿尔山', '阿成被', ]},
    {type: 'B', data: ['北京北', '北京东', '北京', '北京南', '滨江', '北京朝阳', ]},
    {type: 'C', data: ['重庆', '重庆北', '重庆东', '长春', '长春南', '长春西', '成都', '成都东', ]},
    {type: 'D', data: ['大成', '大元', '东方', '丹东', '大网坛', ]},
    {type: 'F', data: ['福州', '福州南', '福建', '复旦', ]},
    {type: 'G', data: ['贵阳', '贵阳东', '广州', '广东', '广州东', '广东北', ]},
    {type: 'H', data: ['哈尔滨', '哈尔滨北', '合肥', '海口', '黄海', '杭州', '呼和浩特', ]},
];


useEffect(() => {
     setTimeout(() => {
         // sectionListRef.current.scrollToLocation({
         //     sectionIndex: 1, // 哪一组
         //     itemIndex: 4, // 组中的哪个item,注意:会把section头算在里面
         //     viewPosition: 0, // 滚动到的位置
         //     animated: true,
         // });
     }, 2000);
 }, []);

const renderItem = ({item, index, section}) => {
    return (
         <Text style={styles.txt}>{item}</Text>
     );
 };
const renderSectionHeader = ({section}) => {
    return (
        <Text style={styles.sectionHeaderTxt}>{section.type}</Text>
    );
}


return (
	// ...
	<SectionList
        ref={sectionListRef}
        style={styles.sectionList}
        sections={SectionData}
        renderItem={renderItem}
        keyExtractor={(item, index) => `${item}-${index}`}
        contentContainerStyle={styles.containerStyle}
        showsVerticalScrollIndicator={false}
        onScroll={(event) => {
            // console.log(event.nativeEvent.contentOffset.y);
        }}
        keyboardDismissMode='on-drag'
        keyboardShouldPersistTaps='handled'
        ListHeaderComponent={
            <View style={styles.header}>
                <Text style={styles.extraTxt}>列表头部</Text>
            </View>
        }
        ListFooterComponent={
            <View style={[styles.header, styles.footer]}>
                <Text style={styles.extraTxt}>列表尾部</Text>
            </View>
        }
        renderSectionHeader={renderSectionHeader}
        ItemSeparatorComponent={() => 
            <View style={styles.separator} />
        }
        stickySectionHeadersEnabled={true}
    />

)
上拉加载----列表组件的属性

1)onEndReached:加载数据函数

2)onEndReachedThreshold:距离底部多少距离触发 0-1

三、RefreshControl下拉刷新组件

1)需要和列表的refreshControl配合使用

2)SectionList,FlatList,ScrollView都可以用

javascript 复制代码
const [refreshing, setRefreshing] = useState(false);
// ...
<SectionList
    // ....忽略
    refreshControl={
        <RefreshControl
            refreshing={refreshing}
            onRefresh={() => {
                console.log('加载...');
                setRefreshing(true);
                setTimeout(() => {
                    setRefreshing(false);
                }, 1000);
            }}
        />
    }
    onEndReached={() => {
        console.log('加载数据...');
    }}
    onEndReachedThreshold={0.2} // 距离底部多少距离触发
/>

四、Modal组件

1)visible:是否显示弹窗

2)onRequestClose:关闭弹窗函数

3)transparent:背景是否透明

4)statusBarTranslucent:状态栏是否透明

5)animationType:动画方式 none/fade/slide

6)onShow:弹窗显示回调

javascript 复制代码
const [visible, setVisible] = useState(true);

// ...
<Button title='按钮' onPress={() =>  setVisible(true)} />
            
<Modal
    visible={visible}
    onRequestClose={() => setVisible(false)}
    transparent={true}
    statusBarTranslucent={true}
    animationType='slide'
    onShow={() => console.log('显示...')}
>

    <View style={styles.bg} />
     <View style={styles.box}>
        <Text style={styles.txt}>我是内容</Text>
    </View>
</Modal>

五、StatusBar组件 - 调整状态栏

1)barStyle:状态栏上的内容的色系 dark-content(黑)/light-content(白)

2)backgroundColor:背景颜色 transparent/white/颜色值

3)translucent:是否透明悬浮

4)hidden:是否隐藏状态栏

javascript 复制代码
<StatusBar
    barStyle='dark-content'
    backgroundColor='transparent'
    translucent={true}
    hidden={true}
/>


六、Switch组件

1)value:指定开关值

2)onValueChange:开关状态回调

3)disabled:是否可切换

4)trackColor:开/关下的背景色 {true: xx, false: xxx}

5)thumbColor:前景颜色

javascript 复制代码
const [switchValue, setSwitchValue] = useState(true);

// ...
<Switch
	  value={switchValue}
	  onValueChange={(value) => {
	      setSwitchValue(value);
	  }}
	  // disabled={false}
	  trackColor={{ true: 'red', false: 'green' }}
	  thumbColor='blue' />
相关推荐
enjoywindstorm2 天前
移动端原生框架对比评测
react native
传奇开心果编程3 天前
【声明式UI开发实用技术学与练】第8课 状态提升与下放
学习·flutter·react native·ui·swiftui·composer
传奇开心果编程4 天前
【现代声明式UI学与练】第4课 列表渲染与 key——如何高效渲染列表、key 的作用、列表重排时的状态保持
学习·flutter·react native·ui·swiftui·android jetpack
传奇开心果编程4 天前
【现代声明式UI学与练】第7课 组件通信——父传子、子传父、跨层级通信、状态提升与 Context
学习·flutter·react native·ui·swiftui·android jetpack
500844 天前
React Native for OpenHarmony 实战:三方库 react-native-url-polyfill 的鸿蒙化适配指南
javascript·react native·react.js·性能优化·electron·harmonyos
传奇开心果编程5 天前
【现代声明式UI学与练】第9课 性能优化——渲染优化、列表优化、内存优化、启动优化
学习·flutter·react native·ui·性能优化·swiftui·android jetpack
500845 天前
React Native for OpenHarmony 实战:三方库 react-native-volume-control 的鸿蒙化适配指南
javascript·react native·react.js·electron·harmonyos
5008410 天前
React Native for OpenHarmony 实战:三方库 react-native-crypto-js 的鸿蒙化适配指南
javascript·react native·性能优化·electron·harmonyos
5008410 天前
React Native for OpenHarmony 实战:三方库 react-native-device-name 的鸿蒙化适配指南
深度学习·react native·react.js·机器学习·harmonyos
5008410 天前
React Native for OpenHarmony 实战:三方库 react-native-torch 的鸿蒙化适配指南
javascript·react native·react.js·harmonyos