React Native - 在状态内的对象上设置状态 [英] React Native - setState on object inside state
本文介绍了React Native - 在状态内的对象上设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在模态屏幕上有两个文本输入,当我填充第一个输入时 - 状态已更新,当我跳转到第二个输入并开始输入时 - 第一个输入的值为空.
I have two text inputs on modal screen, when I'm filling first input - state is updated, and when I jump on second input and start typing - value of the first input is empty.
代码如下:
constructor(){
super()
this.state={
Modal: {
EduModalVisible: false,
ProTitleModalVisible: false,
PsychoModalityModalVisible: false,
},
User: {
NameOfFaculty: '',
YearOfGraduate: '',
}
}
}
文本输入如下所示:
<TextField label={'Faculty'} highlightColor={'#76a6ef'}
value={this.state.User.NameOfFaculty} onChangeText={(faculty) => this.setState({User: { NameOfFaculty: faculty }})} />
<TextField label={'Year Of Graduation'} highlightColor={'#76a6ef'}
value={this.state.User.YearOfGraduate} onChangeText={(year) => this.setState({User: { YearOfGraduate: year }})} />
我认为问题在于更新状态内对象的状态,但我不确定如何解决.
I think that problem is in updating state of object inside state, but I'm not sure how to solve this.
推荐答案
举个例子:https://snack.expo.io/rkeQ7cxWb
您需要为现有对象分配属性以保留其内容:
You need to assign the property for the existing object in order to preserve it contents:
onChangeText={(faculty) => {
const User = Object.assign({}, this.state.User, { NameOfFaculty: faculty });
this.setState({ User });
}}
这篇关于React Native - 在状态内的对象上设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文