以下代码旨在突出显示已按下的按钮。问题是,当一个人按下"否"正如预期的那样,它变成了红色,"是"按钮的背景颜色似乎是黑色而不是蓝色。
this.state = {
color: {
box1: 'blue',
box2: 'blue',
}
}
}
onButtonPressed(value) {
// box1 pressed.
if( value === true ) {
// Change box1 to red, and box2 to blue
this.setState({color:{box1:'red'}})
this.setState({color:{box2:'blue'}})
} else { // box2 pressed
// Change box1 to blue, and box2 to blue
this.setState({ color: { box1: 'blue' } })
this.setState({ color: { box2: 'red' } })
}
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
style={{ backgroundColor: this.state.color.box1 }}
onPress={() => this.onButtonPressed(true)}>
<Text style={styles.boxText}>Yes</Text>
</TouchableHighlight>
<TouchableHighlight
style={{ backgroundColor: this.state.color.box2 }}
onPress={() => this.onButtonPressed(false) }>
<Text style={styles.boxText}>No</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({ 容器: { alignItems:&#39; center&#39;, justifyContent:&#39; center&#39;, backgroundColor:&#39; black&#39;, }, boxText:{ fontSize:100, 颜色:&#39;黑色&#39;, }, });
答案 0 :(得分:1)
问题是你将setState分成2个动作,并覆盖第二个动作上的颜色对象。你只需要将两者合并:
if( value === true ) {
// Change box1 to red, and box2 to blue
this.setState({color:{box1:'red', box2: 'blue'}})
} else { // box2 pressed
// Change box1 to blue, and box2 to blue
this.setState({ color: { box1: 'blue', box2: 'red' } })
}
答案 1 :(得分:1)
<TouchableHighlight activeOpacity={0.6} underlayColor="#DDDDDD" onPress={() => alert('Pressed!')}>
你应该试试这个
答案 2 :(得分:0)
尝试
onButtonPressed(value) {
// box1 pressed.
if( value === true ) {
// Change box1 to red, and box2 to blue
this.setState({color:{box1:'red',box2:'blue'}})
} else { // box2 pressed
// Change box1 to blue, and box2 to blue
this.setState({ color: { box1: 'blue',box2: 'red'}})
}
}