Change color of TouchableOpacity in React Native(在 React Native 中更改 TouchableOpacity 的颜色)
问题描述
谁能帮帮我.这是我的源代码:https://snack.expo.io/rJFgyPDpH
Can anyone help me. This is my source code: https://snack.expo.io/rJFgyPDpH
想法是,如果我点击1 Button"它应该是红色",如果我点击2 Button"也应该改变它的颜色为红色",但 "1 Button" 应更改为其默认颜色,即黑色.但是,2 按钮".
Idea is that, if I click to "1 Button" it should be 'red' and if I click to "2 Button" is also should change its color to 'red' but the "1 Button" should be changed to its default colour which is black. However, "2 Button".
如果我的方法过于简单,也欢迎使用其他方法(如TouchableHighlight
、ES6 等).如果您向我展示错误以便我从中吸取教训,我将不胜感激.
If my approach is too simple, other methods (such as TouchableHighlight
, ES6 and etc) are also welcomed. I appreciate if you show me mistakes so that I learn from that.
推荐答案
你可以这样写代码:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Button,TouchableOpacity} from 'react-native';
export default class App extends Component {
state={
backgroundColor: 'black',
backgroundColor2: 'black',
pressed: false,
};
changeColor(){
if(!this.state.pressed){
this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
} else {
this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
}
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={{backgroundColor:this.state.backgroundColor, padding: 15}}
onPress={()=>this.changeColor()}
>
<Text style={styles.text}>1 Button</Text>
</TouchableOpacity>
<TouchableOpacity
style={{backgroundColor:this.state.backgroundColor2, padding: 15}}
onPress={()=>this.changeColor()}
>
<Text style={styles.text}>2 button!</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
text:{
color:'white'
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
});
现在,如果您单击第一个按钮,它应该是红色",但第二个按钮仍然是黑色"背景.因此,如果您点击第二个按钮,它应该是红色",而第一个按钮应该是黑色".
Now If you click to the first button it should be 'red', but second, remains as 'black' background. Consequently, if you click to second button it should be 'red', whereas the first button should be 'black'.
这篇关于在 React Native 中更改 TouchableOpacity 的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 React Native 中更改 TouchableOpacity 的颜色


- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01