Reputation: 648
The following code seeks to highlight which button has been pressed. The issue is that, while when one presses "No" and it, as expected, turns Red, the "Yes" button's background color seems to be black and not blue.
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>
);
}
}
Here is the styling:
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'black',
},
boxText: {
fontSize: 100,
color: 'black',
},
});
Upvotes: 4
Views: 5423
Reputation: 59
<TouchableHighlight activeOpacity={0.6} underlayColor="#DDDDDD" onPress={() => alert('Pressed!')}>
You should try this one
Upvotes: 4
Reputation: 9978
The problem is that you are splitting the setState into 2 actions, and overriding the color object on the second one. You just need to merge the two:
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' } })
}
Upvotes: 3
Reputation: 1586
Try
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'}})
}
}
Upvotes: 1