RN系統(tǒng)組件三

1. FlatList:一個高性能的列表組件

基礎(chǔ)使用:data酌呆、renderItem衡载、keyExtractor
ScrollView屬性:內(nèi)容容器、滾動條隙袁、滾動監(jiān)聽痰娱、鍵盤模式等
橫向縱向:horizontal
表頭:ListHeaderComponent
表尾:ListFooterComponent
空元素:ListEmptyComponent
分隔線元素:ItemSeparatorComponent
初始渲染元素:initialNumToRender
反向:inverted
多列排布:numColumns
可見元素回調(diào):onViewableItemsChanged
滾動到指定元素:scrollToIndex()、scrollToItem() 不推薦
滾動指定距離:scrollToOffset()
滾動到底:scrollToEnd()

FlatListDemo.js

import { useEffect, useRef } from "react";
import { Text, View, StyleSheet, FlatList } from "react-native";

const data = [
    1, 2,  3, 4, 5, 6, 7, 8, 9, 10,
    11, 12,  13, 14, 15, 16, 17, 18, 19, 20,
]

export default () => {
    const flastRef = useRef(null);
    useEffect(() => {
        setTimeout(() => {
            flastRef.current.scrollToIndex({
                index: 15,
                viewPosition: 1, //0表示頂部菩收,1表示底部
                animated: true
            });
        }, 2000)
    })
    
    const renderItem = ({item, index}) => {
        return (
            <Text style={styles.txt}>{`List item ${item}`}</Text>
        );
    };

    const ListHeader = (
        <View>
            <Text style={styles.txt}>Flast List header</Text>
        </View>
    );

    const ListFooter = (
        <View>
            <Text style={styles.txt}>Flast List Footer</Text>
        </View>
    );

    const ListEmpty = (
        <Text style={styles.listEmpty}>暫無數(shù)據(jù)哦~</Text>
    );

    const ItemSeparator = (
        <View style={styles.divider}></View>
    );

    return(
        <FlatList
            ref={flastRef}
            style={styles.root}
            data={data}
            // data={[]}
            renderItem={renderItem}
            keyExtractor={(item, index) => `item-${index}` }
            ListHeaderComponent={ListHeader}
            ListFooterComponent={ListFooter}
            ListEmptyComponent={ListEmpty}
            ItemSeparatorComponent={ItemSeparator}
            initialNumToRender={15}
            // inverted={true}
            // numColumns={2}
            onViewableItemsChanged={(info) => {
                const {viewableItems} = info;
                console.log(viewableItems);
            }}
        >

        </FlatList>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f0f0f0',
    },
    txt: {
        fontSize: 20,
        fontWeight: 'bold',
        margin: 20
    },
    listEmpty: {
        width: '100%',
        height: 500,
        fontSize: 20,
        fontWeight: 'bold',
        textAlign: 'center',
        textAlignVertical: 'center'
    },
    divider: {
        width: '100%',
        height: 0.5,
        backgroundColor: '#dedede',
    },
});

2. SectionList:強中之強梨睁,多類型分組列表

基礎(chǔ)使用:sections、renderItem娜饵、keyExtractor
ScrollView屬性:內(nèi)容容器坡贺、滾動條、滾動監(jiān)聽、鍵盤模式等
表頭:ListHeaderComponent
表尾:ListFooterComponent
分組頭部:renderSectionHeader
分割線元素:ItemSeparatorComponent
分組吸頂:stickySectionHeadersEnabled
滾動api:scrollToLocation()

import { View, StyleSheet, SectionList, Text } from "react-native"
import { SectionData } from "../constants/Data";
import { useEffect, useRef } from "react";

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

    const renderSectionHeader = ({section}) => {
        return (
            <Text style={styles.sectionHeader}>{section.type}</Text>
        );
    };

    const sectionListRef = useRef(null);
    useEffect(() => {
        setTimeout(() => {
            sectionListRef.current.scrollToLocation({
                sectionIndex: 1,
                itemIndex: 2,
                // viewPosition: 0,
                
            });
        }, 2000);
    }, []);
    
    return (
        <SectionList
            ref={sectionListRef}
            style={styles.root}
            sections={SectionData}
            renderItem={renderItem}
            keyExtractor={(item, index) => `item-${index}`}
            renderSectionHeader={renderSectionHeader}
            stickySectionHeadersEnabled={true}
        >

        </SectionList>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f0f0f0',
    },
    txt: {
        fontSize: 20,
        height: 56,
        width: '100%',
        color: "#333",
        textAlignVertical: 'center',
        textAlign: 'center'
    },
    sectionHeader: {
        width: '100%',
        height: 36,
        backgroundColor: 'red',
        textAlign: 'center',
        fontSize: 22,
    }
});

3. RefreshControl:下拉刷新遍坟,上拉加載拳亿,用我沒錯

下拉刷新:refreshing、onRefresh
上拉加載:onEndReached政鼠、onEndReachedThreshold

import { View, StyleSheet, SectionList, Text, RefreshControl } from "react-native"
import { SectionData } from "../constants/Data";
import { useEffect, useRef, useState } from "react";

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

    const renderSectionHeader = ({section}) => {
        return (
            <Text style={styles.sectionHeader}>{section.type}</Text>
        );
    };

    const sectionListRef = useRef(null);
    const [refreshing, setRefreshing] = useState(false)

    // useEffect(() => {
    //     setTimeout(() => {
    //         sectionListRef.current.scrollToLocation({
    //             sectionIndex: 1,
    //             itemIndex: 2,
    //             // viewPosition: 0,
                
    //         });
    //     }, 2000);
    // }, []);
    
    return (
        <SectionList
            ref={sectionListRef}
            style={styles.root}
            sections={SectionData}
            renderItem={renderItem}
            keyExtractor={(item, index) => `item-${index}`}
            renderSectionHeader={renderSectionHeader}
            stickySectionHeadersEnabled={true}
            refreshControl={
                <RefreshControl
                    refreshing={refreshing}
                    onRefresh={() => {
                        console.log("onRefresh...");
                        setRefreshing(true);
                        //request new data
                        setTimeout(() => {
                            setRefreshing(false);
                        }, 2000)
                    }}
                    
                >
                </RefreshControl>
            }
            onEndReached={() => {
                console.log('onEndReached...')
            }}
            onEndReachedThreshold={0.3}
        >

        </SectionList>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f0f0f0',
    },
    txt: {
        fontSize: 20,
        height: 56,
        width: '100%',
        color: "#333",
        textAlignVertical: 'center',
        textAlign: 'center'
    },
    sectionHeader: {
        width: '100%',
        height: 36,
        backgroundColor: 'red',
        textAlign: 'center',
        fontSize: 22,
    }
});

4. Modal:實現(xiàn)不同樣式的彈窗

控制顯示:visible
渲染內(nèi)容:children
安卓返回關(guān)閉:onRequestClose
背景透明:transparent
狀態(tài)欄透明:statusBarTranslucent
動畫方式:animationType
狀態(tài)回調(diào):onShow风瘦、onDismiss
背景動畫:伏筆

ModalDemo.js

import { View, StyleSheet, Modal, Text, SectionList, Button, Image, TouchableOpacity } from "react-native"
import { SectionData } from "../constants/Data";
import { useRef, useState } from "react";
import close from "../assets/images/icon_close_modal.png"

export default () => {
    const [visible, setVisible] = useState(false);

    const showModal = () => {
        setVisible(true);
    }

    const hideModal = () => {
        setVisible(false);
    }



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

    const renderSectionHeader = ({ section }) => {
        return (
            <View style={styles.sectionHeader}>
                <Text style={styles.sectionHeader}>{section.type}</Text>
            </View>


        );
    };

    const listHeader = () => {
        return (
            <View style={styles.listHeader}>
                <Text style={styles.listHeader}>
                    列表頭部
                </Text>
                <TouchableOpacity
                    style={styles.iconButton}
                    onPress={() => {
                        hideModal()
                    }}
                >
                    <Image
                        source={close}
                        style={styles.icon}
                    />
                </TouchableOpacity>
            </View>

        );
    }

    return (
        <View style={styles.root}>
            <Button title="按鈕" onPress={() => {
                showModal();
            }} />
            <Modal
                visible={visible}
                onRequestClose={() => {
                    hideModal();
                }}
                transparent={true}
                // statusBarTranslucent={true}
                animationType="slide"
                onShow={() => {
                    console.log('onShow...')
                }}
                onDismiss={() => {
                    //有問題,不回調(diào)
                    console.log('onDismiss...')
                }}
            >
                <View style={styles.blank}></View>
                <View style={styles.content}>
                    <SectionList
                        style={styles.sectionList}
                        sections={SectionData}
                        renderItem={renderItem}
                        keyExtractor={(item, index) => `item-${index}`}
                        renderSectionHeader={renderSectionHeader}
                        stickySectionHeadersEnabled={true}
                        ListHeaderComponent={listHeader}
                    >

                    </SectionList>
                </View>
            </Modal>
        </View>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        padding: 20,
    },
    content: {
        width: '100%',
        height: '90%',
        backgroundColor: "#ff000030"
    },
    sectionList: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f0f0f0',
    },
    txt: {
        fontSize: 20,
        height: 56,
        width: '100%',
        color: "#333",
        textAlignVertical: 'center',
        textAlign: 'center'
    },
    sectionHeader: {
        width: '100%',
        height: 36,
        backgroundColor: 'red',
        textAlign: 'center',
        fontSize: 22,
        justifyContent: 'center'
    },
    blank: {
        width: '100%',
        height: '10%',
        backgroundColor: '#00000050'
    },
    icon: {
        width: 24,
        height: 24,
    },
    iconButton: {
        // width: 24,
        // height: 24,
        position: 'absolute',
        right: 16
    },
    listHeader: {
        width: '100%',
        height: 36,
        backgroundColor: 'yellow',
        textAlign: 'center',
        fontSize: 22,
        justifyContent: 'center',
        textAlignVertical: 'center'
    },
})

5. StatusBar:狀態(tài)欄適配的難題交我

內(nèi)容深淺模式:barStyle
背景顏色:backgroundColor
動畫切換:animated
透明懸腹恪:translucent
隱藏狀態(tài)欄:hidden
api:setBackgroundColor()万搔、setBarStyle()、setHidden()官帘、setTranslucent()

<StatusBar 
                barStyle={"dark-content"}
                backgroundColor='white'
                // animated={true}
                // translucent={true}
                hidden={false}
            />

6. Switch:開關(guān)切換瞬雹,一鍵搞定

指定開關(guān):value
狀態(tài)回調(diào):onValueChange
設(shè)置不可用:disabled
背景顏色:trackColor
前景顏色:thumbColor

import { useState } from "react";
import { View, StyleSheet, Switch } from "react-native"


export default()=> {
    const [switchValue, setSwitchValue] = useState(false);

    return (
        <View style={styles.root}>
            <Switch 
                value={switchValue}
                onValueChange={(value) => {
                    console.log(`value: ${value}`)
                    setSwitchValue(value);
                }}
                // disabled={true}
                trackColor={{true: 'red', false: 'yellow'}}
                thumbColor='#0f0'
            />
        </View>
    );
}

const styles = StyleSheet.create({
    root: {
        width: '100%',
        height: '100%',
        backgroundColor: '#f0f0f0'
    }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市刽虹,隨后出現(xiàn)的幾起案子酗捌,更是在濱河造成了極大的恐慌,老刑警劉巖涌哲,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件胖缤,死亡現(xiàn)場離奇詭異,居然都是意外死亡阀圾,警方通過查閱死者的電腦和手機哪廓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來初烘,“玉大人涡真,你說我怎么就攤上這事∩隹穑” “怎么了哆料?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長吗铐。 經(jīng)常有香客問我东亦,道長,這世上最難降的妖魔是什么唬渗? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任典阵,我火速辦了婚禮,結(jié)果婚禮上谣妻,老公的妹妹穿的比我還像新娘。我一直安慰自己卒稳,他們只是感情好蹋半,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著充坑,像睡著了一般减江。 火紅的嫁衣襯著肌膚如雪染突。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天辈灼,我揣著相機與錄音份企,去河邊找鬼。 笑死巡莹,一個胖子當(dāng)著我的面吹牛司志,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播降宅,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼骂远,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了腰根?” 一聲冷哼從身側(cè)響起激才,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎额嘿,沒想到半個月后瘸恼,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡册养,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年东帅,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片捕儒。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡冰啃,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刘莹,到底是詐尸還是另有隱情阎毅,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布点弯,位于F島的核電站扇调,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏抢肛。R本人自食惡果不足惜狼钮,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望捡絮。 院中可真熱鬧熬芜,春花似錦、人聲如沸福稳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鼓拧,卻和暖如春半火,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背季俩。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工钮糖, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人酌住。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓店归,卻偏偏與公主長得像,于是被迫代替她去往敵國和親赂韵。 傳聞我的和親對象是個殘疾皇子娱节,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容