美文网首页
RN系统组件二

RN系统组件二

作者: zhang_pan | 来源:发表于2024-03-27 09:01 被阅读0次

    1. TouchableOpacity:最好用的点击组件

    透明度渐变阈值:activeOpacity
    点击事件:onPress、onLongPress、delayLongPress
    点击事件起止:onPressIn、onPressOut

    TouchableOpacityDemo.js

    import { StyleSheet, TouchableOpacity, View, Text } from "react-native"
    
    export default() => {
        return <View style={styles.root}>
            <TouchableOpacity 
                style={styles.button}
                activeOpacity={0.7}  //x~1不透明度变化范围
                onPress={() => {
                    console.log('onPress...')
                }}
                onLongPress={() => {
                    console.log('onLongPress...')
                }}
                delayLongPress={1000}
            >
                <Text style={styles.txt}>
                    按钮
                </Text>
            </TouchableOpacity>
        </View>
    }
    
    const styles = StyleSheet.create({
        root: {
            width: '100%',
            height: '100%',
            backgroundColor: '#f0f0f0'
        },
        button: {
            width: 300,
            height: 65,
            backgroundColor: '#FF0',
            justifyContent: 'center',
            alignItems: 'center',
        },
        txt: {
            fontSize: 20,
            color: 'black',
            fontFamily: 'bold'
        }
    });
    

    2. TouchableHighlight:稍显麻烦但效果丰富的点击组件

    所有点击类事件和TouchableOpacity相同
    只支持一个子节点
    使用陷阱:必须复写onPress

    TouchableHighlightDemo.js

    import { View, StyleSheet, TouchableHighlight, Text } from "react-native"
    
    export default() => {
        return <View style={styles.root}>
            <TouchableHighlight 
                style={styles.button}
                activeOpacity={0.7}
                onPress={() => {
                    console.log('onPress...')
                }}
                underlayColor='#00bcd4'
            >
                <Text style={styles.txt}>
                    按钮
                </Text>
            </TouchableHighlight>
        </View>
    }
    
    const styles = StyleSheet.create({
        root: {
            width: '100%',
            height: '100%',
            backgroundColor: '#f0f0f0'
        },
        button: {
            width: 300,
            height: 65,
            backgroundColor: '#FF0',
            justifyContent: 'center',
            alignItems: 'center',
        },
        txt: {
            fontSize: 20,
            color: 'black',
            fontFamily: 'bold'
        }
    });
    
    
    

    3. TouchableWithoutFeedback:很少使用的点击组件

    官方文档:除非你有一个很好的理由,否则不要用这个组件。所有能够响应触屏操作的元素在触屏后都应该有一个视觉上的反馈。
    只支持一个子节点,且自身不支持样式

    <TouchableWithoutFeedback>
                <View style={styles.button}>
                    <Text style={styles.txt}>按钮</Text>
                </View>
    </TouchableWithoutFeedback>
    

    4. Button:固定格式的点击组件,优点使用简单

    title:设置按钮显示文字,color:设置按钮颜色
    disabled: 设置按钮不可点击
    onPress: 设置按钮点击事件

    ButtonDemo.js

    import { Button, StyleSheet, View } from "react-native"
    
    export default ()  => {
        return <View style={styles.root}>
            <Button 
                title="按钮"
                color={'green'}
                onPress={() => {
                    console.log('onPress...')
                }}
                // disabled={false}
            />
        </View>
    }
    
    const styles = StyleSheet.create({
        root: {
            width: '100%',
            height: '100%',
            backgroundColor: '#f0f0f0'
        }
    });
    

    5. 强大的Pressable,帮你实现复杂的交互效果(新)

    点击类事件和其它点击组件一致
    带状态样式与带状态子节点
    代码简写

    PressableDemo.js

    import { View, StyleSheet, Pressable, Text } from "react-native"
    
    export  default () => {
        return <View style={styles.root}>
            <Pressable style={(state) => {
                const { pressed } = state;
                return [styles.button, pressed && styles.buttonPressed]
            }}>
                {(state) =>  {
                    const { pressed } = state;
                    return <Text style={pressed ? styles.txtPressed : styles.txt}>按钮</Text>
                }}
            </Pressable>
        </View>
    }
    
    const styles = StyleSheet.create({
        root: {
            width: '100%',
            height: '100%',
            backgroundColor: '#F0F0F0',
            margin: 10
        },
        button: {
            width: 300,
            height: 65,
            backgroundColor: "#2030FF",
            justifyContent: 'center',
            alignItems: 'center',
            borderRadius: 10,
        },
        buttonPressed: {
            backgroundColor: "white",
        },
    
        txt: {
            color: 'white',
            fontSize: 20,
            fontFamily: 'bold'
        },
        txtPressed: {
            color: '#2030FF',
            fontSize: 20,
            fontFamily: 'bold'
        }
    });
    

    简写为:

    export  default () => {
        return <View style={styles.root}>
            <Pressable style={state => [styles.button, state.pressed && styles.buttonPressed]}>
                {state => <Text style={state.pressed ? styles.txtPressed : styles.txt}>按钮</Text>}
            </Pressable>
        </View>
    }
    

    6. ScrollView:基础滚动组件,快速实现列表渲染

    添加子节点:固定子元素、列表渲染、数组渲染
    内容包裹样式:contentContainerStyle
    滚动键盘消失:keyboardDismissMode
    点击收起键盘:keyboardShouldPersistTaps
    滚动开始与结束:onMomentumScrollBegin/End
    滚动距离监听:onScroll(iOS:scrollEventThrottle)
    超出滚动:overScrollMode
    分页滚动:pagingEnabled,滚动方向:horizontal
    初始滚动:contentOffset
    是否展示滚动条:showVerticalScrollIndicator/Horizontal
    吸顶元素:stickyHeaderIndices
    api:scrollTo()、scrollToEnd()

    import { useRef } from "react";
    import { View, StyleSheet, ScrollView, Text, TextInput, Button, Dimensions } from "react-native";
    
    export default () => {
        let { width } = Dimensions.get('window');
        // 3.数组渲染
        const buildListView = () => {
            const array = [];
            for (let i = 6; i < 20; i++) {
                array.push(
                    <Text key={`item-${i}`} style={styles.txt}>{`List item ${i}`}</Text>
                )
            }
            return array;
        };
    
        const array = [1, 2, 3, 4, 5];
    
        const scrollViewRef = useRef(null);
    
        return (
            <View style={styles.root}>
                {/* 分页滚动 */}
                <ScrollView style={{ width: '100%',  height: 200 }} horizontal={true} pagingEnabled={true}>
                    <View style={{ width, height: '100%', backgroundColor: 'yellow' }}></View>
                    <View style={{ width, height: '100%', backgroundColor: 'blue' }}></View>
                    <View style={{ width, height: '100%', backgroundColor: 'red' }}></View>
                </ScrollView>
                <ScrollView
                    ref={scrollViewRef}
                    contentContainerStyle={styles.containerStyle}
                    keyboardDismissMode='on-drag'
                    keyboardShouldPersistTaps='handled'
                    onMomentumScrollBegin={() => {
                        // console.log('onMomentumScrollBegin..')
                    }}
                    onMomentumScrollEnd={() => {
                        // console.log('onMomentumScrollEnd..')
                    }}
                    onScroll={(event) =>  {
                        let y = event.nativeEvent.contentOffset.y
                        console.log('onScroll..' + y)
                    }}
                    scrollEventThrottle={16}
                    overScrollMode="never"
                    contentOffset={{ y: 100 }}
                    showsVerticalScrollIndicator={ false }
                    stickyHeaderIndices={[0]}
                >
                    <TextInput style={styles.input}></TextInput>
                    <Button title="按钮" onPress={() => {
                        console.log('onPress..')
                        // scrollViewRef.current.scrollTo({y: 300, animted: true})
                        scrollViewRef.current.scrollToEnd({animted: true})
                    }}/>
                    {/* 1.固定子元素 */}
                    <Text style={styles.txt}>A</Text>
                    <Text style={styles.txt}>A</Text>
                    <Text style={styles.txt}>A</Text>
                    <Text style={styles.txt}>A</Text>
    
                    {/* 2.列表渲染 */}
                    { array.map((item, index) => {
                        return <Text key={`item-${index}`} style={styles.txt}>{`List item ${item}`}</Text>
                    })}
                    { buildListView() }
                </ScrollView>
            </View>
        );
    }
    
    const styles = StyleSheet.create({
        root: {
            width: '100%',
            height: '100%',
            backgroundColor: '#f0f0f0'
        },
        txt: {
            fontSize: 20,
            fontWeight: 'bold',
            margin: 20,
        },
        containerStyle:  {
            paddingHorizontal: 16,
            backgroundColor: '#e0e0e0',
            paddingTop: 16,
        },
        input: {
            width: '100%',
            height: 60,
            backgroundColor: '#ff000050',
        }
    });
    

    相关文章

      网友评论

          本文标题:RN系统组件二

          本文链接:https://www.haomeiwen.com/subject/bozetjtx.html