如何解决在 React Native 中,是否有类似于新 Pressable 组件中的 activeOpacity 道具的东西?
在 TouchableOpacity 中,可以设置 activeOpacity 属性的值在按钮被按下后使按钮变暗,因此用户有反馈说他们的触摸被注册并且不会重复按下同一个按钮。
新的 Pressable 组件中是否有类似的东西?或者有什么方法可以轻松达到同样的效果?
解决方法
您可以尝试以下示例来实现相同的功能:
import React,{ useState } from 'react';
import { Pressable,StyleSheet,Text,View } from 'react-native';
const App = () => {
const [timesPressed,setTimesPressed] = useState(0);
let textLog = '';
if (timesPressed > 1) {
textLog = timesPressed + 'x onPress';
} else if (timesPressed > 0) {
textLog = 'onPress';
}
return (
<View style={styles.container}>
<Pressable
onPress={() => {
setTimesPressed((current) => current + 1);
}}
style={({ pressed }) => [
{
backgroundColor: 'gray',opacity: pressed ? 0.2 : 1
},styles.wrapperCustom
]}>
{({ pressed }) => (
<Text style={styles.text}>
{pressed ? 'Pressed!' : 'Press Me'}
</Text>
)}
</Pressable>
<View style={styles.logBox}>
<Text testID="pressable_press_console">{textLog}</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,justifyContent: "center",},text: {
fontSize: 16
},wrapperCustom: {
borderRadius: 8,padding: 6
},logBox: {
padding: 20,margin: 10,borderWidth: StyleSheet.hairlineWidth,borderColor: '#f0f0f0',backgroundColor: '#f9f9f9'
}
});
export default App;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。