【发布时间】:2018-10-23 02:39:05
【问题描述】:
目前,我正在使用一个函数来切换 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'} }]}>
有什么更好的/正确的方法来做到这一点?
【问题讨论】:
标签: react-native styling ternary-operator