我是编码新手,也是 React 新手,我尝试通过单击更改我的文本颜色(然后再次单击以更改回原始颜色)。
function lastTouches() {
return (
<Box>
<Box>
<TouchableOpacity>
<Text>
Change Color
</Text>
</TouchableOpacity>
</Box>
);
}
export default lastTouches;
答案 0 :(得分:0)
如果要更改按钮的文本,则必须为 <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;
答案 1 :(得分:-1)
首先从react导入usestate;
Name total_logins
----
Steve 4
Alice 2
May 2
Peter 1
William 1
它会起作用!对于 React Js,使用按钮和调用函数;