我的按钮没有改变颜色。这是我的代码:
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
const MyButton = () => {
const [isPressed, setIsPressed] = React.useState(false);
const handlePressIn = () => {
setIsPressed(true);
};
const handlePressOut = () => {
setIsPressed(false);
};
return (
<TouchableOpacity
onPressIn={handlePressIn}
onPressOut={handlePressOut}
style={[styles.button, isPressed && styles.buttonPressed]}
>
<Text style={styles.buttonText}>Press Me</Text>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
button: {
backgroundColor: 'blue',
padding: 10,
borderRadius: 5,
},
buttonPressed: {
backgroundColor: 'red',
},
buttonText: {
color: 'white',
fontSize: 16,
},
});
export default MyButton;
我做错了什么?按钮不会改变颜色。需要帮忙。谢谢!您的文字
我尝试在按下按钮时更改颜色。预计按钮会变成红色,但保持蓝色。
我认为本质上,使用
TouchableOpacity
来解决这个问题会很棘手,所以我不建议在这种情况下使用它,因为它已经有自己的行为来处理触摸反馈。您正在寻找的内容如下所示,但使用react-native的 Pressable
组件代替,就像这样简单:
<Pressable
style={({pressed}) => [
styles.button,
{
backgroundColor: pressed ? 'red' : 'blue',
},
styles.wrapperCustom,
]}
>
<Text style={styles.buttonText}>Press Me</Text>
</Pressable>