问题
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.
Here is code:
constructor(){
super()
this.state={
Modal: {
EduModalVisible: false,
ProTitleModalVisible: false,
PsychoModalityModalVisible: false,
},
User: {
NameOfFaculty: '',
YearOfGraduate: '',
}
}
}
And text input looks like this:
<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.
回答1:
Here's an example: 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 });
}}
来源:https://stackoverflow.com/questions/44117724/react-native-setstate-on-object-inside-state