如果要更改按钮的文本,则必须为 <Text> 组件定义样式。
<Text style={{ color: /* state value here */ }}>Press Here</Text>
示例
下面的代码是文档中功能组件示例的一个分支。
见:React Native / Docs / TouchableOpacity
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10,
border: "thin solid grey"
}
});
const App = () => {
const [active, setActive] = useState(false);
const onPress = () => setActive(!active);
const buttonTextStyle = {
color: active ? 'green' : 'red'
};
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={onPress}
>
<Text style={buttonTextStyle}>Press Here</Text>
</TouchableOpacity>
</View>
);
};
export default App;
如果您希望每个按钮独立运行,则需要创建一个新组件。
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10,
gap: 10
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
padding: 10,
border: "thin solid grey"
}
});
const StatefulButton = (props) => {
const { color, activeColor } = props;
const [active, setActive] = useState(false);
const onPress = () => setActive(!active);
const buttonTextStyle = {
color: active ? activeColor : color,
fontStyle: active ? 'unset' : 'italic',
fontWeight: active ? 'bold' : 'normal'
};
return (
<TouchableOpacity style={styles.button} onPress={onPress}>
<Text style={buttonTextStyle}>Press Here</Text>
</TouchableOpacity>
);
};
const App = () => {
return (
<View style={styles.container}>
<StatefulButton color="red" activeColor="green" />
<StatefulButton color="magenta" activeColor="cyan" />
</View>
);
};
export default App;