react-native - 使用三元运算符更改背景颜色的更好方法
问题描述
目前,我正在使用一个函数来切换 hasBeenClicked,然后我使用条件来确保仅当 hasBeenClicked 为 true 时才更改背景颜色。我更喜欢在 style 道具中使用三元运算符来处理逻辑。
let randomHex = () => {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
// console.log('here is your random hex color', color);
}
return color;
}
export default class App extends Component {
constructor() {
super()
this.state = {
hasBeenClicked: false
}
}
changeColor = () => {
this.setState({
hasBeenClicked: !this.state.hasBeenClicked
})
if (this.state.hasBeenClicked === true) {
this.setState({
backgroundColor: randomHex()
})
}
}
render() {
return (
<View style={[styles.container, { backgroundColor: this.state.backgroundColor }]}>
<TouchableOpacity
onPress={this.changeColor}
>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
</TouchableOpacity>
</View>
);
}
}
我试过了
<View style={[styles.container, { backgroundColor: {this.state.hasBeenClicked: this.state.backgroundColor ? 'green'} }]}>
有什么更好的方法/正确的方法来做到这一点?
解决方案
你的三元不正确:
{ this.state.hasBeenClicked : this.state.backgroundColor ? 'green'}
应该
{ this.state.hasBeenClicked ? this.state.backgroundColor : 'green'}
推荐阅读
- postgresql - 连接到较旧的 Postgresql 数据库
- javascript - 制作 React Native 多行文本输入,在拖动时隐藏键盘并且不隐藏光标
- docker - 我不知道如何做同样的事情拉,创建和启动,而不是 docker run -dti
- ios - 如何快速检查类型并将其转换为 Decodable
- vb.net - 在 VB.NET 中,对象引用周围的括号到底是做什么的?
- python - 在 python tkinter 输入框中登录后显示用户名
- java - Java Stream - 结合过滤和收集
- nestjs - Nest js上传不保存文件
- vue.js - 如何使用计算属性对本地存储的更改做出反应
- python - python Xpath:如何删除空标签但保留同级尾随文本?