我不明白为什么组件在 setState 之后没有重新渲染。我认为绑定(bind) onPress 方法会有所帮助,但事实并非如此。 当我点击 TouchableHighlight 时,它会更改 View 背景颜色,但如果我再次点击它,它就不会再改变。
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>
);
}
}
最佳答案
问题似乎是您如何在函数中设置currentColor
。按照您的做法并不能保证您将获得适合您的 setState
的 currentColor
值。 React's documentation建议使用提供给 setState
的 state
参数:
// 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',
}));
};
关于javascript - React Native 在 setState 之后不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59829919/