网页设计论文致谢北京网站优化经理
在 React Native 中要实现可触摸的组件方式有三种,第一种方式就是使用TouchableHighlight
组件,第二种方式就是使用TouchableOpacity
组件,最后一种方式就是使用TouchableWithoutFeedback
组件。
TouchableHighlight
TouchableHighlight
组件主要是响应触摸的组件。当用户按下此组件时,此组件的亮度会变成高亮显示(由透明改为不透明),从而让用户感知到进行了交互。TouchableHighlight
假如不设置underlayColor
属性的话,underlayColor 的默认值为黑色。假如此组件的子元素也有样式的话,可能会发生颜色重叠导致一些问题。
TouchableHighlight
组件必须有一个子级(不能为零个或多个)。如果您希望有多个子组件,请将它们包装在视图中。具体实例如下:
import { StyleSheet, Text, TouchableHighlight, View } from "react-native";
import React, { useState } from "react";export default function TouchComponent() {const [count, setCount] = useState<number>(0);return (<View style={styles.container}><Text style={styles.mainTitle}>触摸组件实例</Text><TouchableHighlightactiveOpacity={0.4}underlayColor="#DDDDDD"onPress={() => setCount(count + 1)}><View style={styles.button}><Text>点击加1</Text></View></TouchableHighlight><Text>{count}</Text></View>);
}const styles = StyleSheet.create({container: {margin: 8,},mainTitle: {fontSize: 22,fontWeight: "bold",padding: 10,borderBottomWidth: 1,borderColor: "#e3e3e3",},button: {alignItems: "center",backgroundColor: "#DDDDDD",padding: 10,},
});
TouchableOpacity
TouchableOpacity
组件跟TouchableHighlight
的作用一致,此组件的透明度会发生改变(由不透明改为透明),从而能让用户感知到进行了交互。假如此组件的子元素也有样式的话,可能会发生颜色重叠导致一些问题。
通过将子组件包装在 Animated.View 中(添加到视图层次结构中)来控制不透明度。请注意,这可能会影响布局。具体的实例如下:
import {StyleSheet,Text,TouchableHighlight,TouchableOpacity,View,
} from "react-native";
import React, { useState } from "react";export default function TouchComponent() {const [count, setCount] = useState<number>(0);return (<View style={styles.container}><Text style={styles.mainTitle}>触摸组件实例</Text><TouchableOpacity onPress={() => setCount(count + 1)}><Text style={styles.button}>点击加1</Text></TouchableOpacity><Text>{count}</Text></View>);
}const styles = StyleSheet.create({container: {margin: 8,},mainTitle: {fontSize: 22,fontWeight: "bold",padding: 10,borderBottomWidth: 1,borderColor: "#e3e3e3",},button: {alignItems: "center",backgroundColor: "#DDDDDD",padding: 10,},
});
TouchableWithoutFeedback
TouchableWithoutFeedback
此组件是不会发生任何视觉反馈信息的。TouchableWithoutFeedback 仅支持一个孩子。如果您希望有多个子组件,请将它们包装在视图中。重要的是,TouchableWithoutFeedback 的工作原理是克隆其子级并向其应用响应者道具。因此,任何中间组件都需要通过这些 props 传递给底层的 React Native 组件。
import {StyleSheet,Text,TouchableHighlight,TouchableOpacity,TouchableWithoutFeedback,View,
} from "react-native";
import React, { useState } from "react";export default function TouchComponent() {const [count, setCount] = useState<number>(0);return (<View style={styles.container}><Text style={styles.mainTitle}>触摸组件实例</Text><TouchableWithoutFeedback onPress={() => setCount(count + 1)}><View style={styles.button}><Text>点击加1</Text></View></TouchableWithoutFeedback><Text>{count}</Text></View>);
}const styles = StyleSheet.create({container: {margin: 8,},mainTitle: {fontSize: 22,fontWeight: "bold",padding: 10,borderBottomWidth: 1,borderColor: "#e3e3e3",},button: {alignItems: "center",backgroundColor: "#DDDDDD",padding: 10,},
});