在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;

TL;DR

<Pressable
style={({ pressed }) => [
{ opacity: pressed ? 0.2 : 1}, styles.wrapperCustom,
]}>
{({ pressed }) => (
<Text style={styles.text}> {pressed ? 'Pressed!' : 'Press Me'} </Text>
)}
</Pressable>

相关内容

  • 没有找到相关文章

最新更新