gpt4 book ai didi

javascript - React Native 在 setState 之后不重新渲染

转载 作者:行者123 更新时间:2023-12-02 22:02:35 24 4
gpt4 key购买 nike

我不明白为什么组件在 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。按照您的做法并不能保证您将获得适合您的 setStatecurrentColor 值。 React's documentation建议使用提供给 setStatestate 参数:

// 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com