ReactNative 基础组件二

1. TouchableHighlight

TouchableHighlight 是一个组件,用于在用户触摸时高亮显示其子组件它通常用于按钮或其他可点击元素。

import React from 'react';
import { View, Text, TouchableHighlight } from 'react-native';

const MyComponent = () => {
  return (
    <View style={styles.container}>
      <TouchableHighlight
        style={styles.button}
        onPress={() => console.log('Button pressed')}
        underlayColor="#f1f1f1"
      >
        <Text style={styles.buttonText}>Click me</Text>
      </TouchableHighlight>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    backgroundColor: '#007bff',
    padding: 10,
    borderRadius: 5,
    width: '80%',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default MyComponent;

在上面的示例中,我们使用 TouchableHighlight 组件来创建一个可以点击的按钮。我们使用 onPress prop 来指定当用户点击按钮时要执行的操作,并使用 underlayColor prop 来指定高亮显示时的背景颜色。

API 说明
  • onPress: 当用户点击组件时调用的回调函数。
  • onLongPress: 当用户长按组件时调用的回调函数。
  • underlayColor: 指定高亮显示时的背景颜色。
  • activeOpacity: 指定高亮显示时的不透明度。
  • style: 指定组件的样式。

2. TouchableOpacity

API 说明
  • 透明度渐变阈值:activeOpacity
  • 点击事件:onPressonLongPressdelayLongPress
  • 点击事件起止:onPressInonPressOut

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'
    }
});

3.TouchableWithoutFeedback

TouchableWithoutFeedback 是一个组件,用于在用户触摸时执行某个操作,但不提供任何视觉反馈。它通常用于需要隐藏点击效果的场景。

示例代码

import React from 'react';
import { View, Text, TouchableWithoutFeedback } from 'react-native';

const MyComponent = () => {
  return (
    <View style={styles.container}>
      <TouchableWithoutFeedback
        onPress={() => console.log('Button pressed')}
      >
        <View style={styles.button}>
          <Text style={styles.buttonText}>Click me</Text>
        </View>
      </TouchableWithoutFeedback>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    backgroundColor: '#007bff',
    padding: 10,
    borderRadius: 5,
    width: '80%',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

export default MyComponent;

在上面的示例中,我们使用 TouchableWithoutFeedback组件来创建一个可以点击的按钮。我们使用 onPress prop 来指定当用户点击按钮时要执行的操作。

API 说明

  • onPress: 当用户点击组件时调用的回调函数。
  • onLongPress: 当用户长按组件时调用的回调函数。
  • style: 指定组件的样式。

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',
    }
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容