Reputation: 203
I don't understand why the component is not being re-rendered after the setState. I thought binding the onPress method would help but it didn't. When I tap on the TouchableHighlight it changes the View backgroundColor, although if I tap it again wont change ever again.
class Item extends Component{
state={
currentColor:"#FFFFF"
}
onClick() {
console.log(this.state.currentColor)
if (this.state.currentColor=='#FFFFF'){
color='green'
} else {
color='#FFFFF'
}
this.setState({currentColor:color})
}
render(){
return (
<TouchableHighlight onPress={ this.onClick.bind(this) } >
<View style={[styles.item, {backgroundColor: this.state.currentColor}]}>
<Text style={styles.title}>{this.props.title}</Text>
</View>
</TouchableHighlight>
);
}
}
Upvotes: 0
Views: 408
Reputation: 183
The issue seems to be how you set currentColor
in your function. Doing it as you did doesn't certify that you'll get the proper currentColor
value for you setState
. React's documentation suggests using the state
argument provided to setState
:
// no need to bing if you use an arrow function here
onClick = () => {
console.log(this.state.currentColor);
this.setState(state => ({
currentColor: state.currentColor === '#FFF' ? 'red' : '#FFF',
}));
};
Upvotes: 1