为textInput没有得到重新渲染时状态改变
问题描述:
我现在有这个功能,这使得在textInput用不同的占位符,每种状态:为textInput没有得到重新渲染时状态改变
_renderSimpleForm =() => {
return (
<View style={styles.simpleContainer}>
<TextInput
style={[styles.textContentWhite, styles.textContentWhiteHeight, styles.indentLeft]}
placeholder={this.state.form.userInput}
placeholderTextColor="#B7BEDE"
onChangeText={(userInputValue) =>
//TODO: Saving text to nested userInput is causing problem, temporarily save it to userInputValue
//this.setState({form: {...this.state.form, userInput: text}}
this.setState({userInputValue}
)}
//onSubmitEditing={this._submitInfo()}
/>
<View style={styles.whiteLine}/>
</View>
);
}
但是以后每次状态变化,从价值之前的状态仍然存在于textInput中。我认为这个textInput会在状态发生变化时使用新的placeHolder值重新呈现。我在这里做错了什么?
我的状态对象是如下:
const states = {
//TODO: including GPA and coursework
schoolForm: {
prompt: "Where did you go to school?",
userInput: "School name",
},
durationForm: {
prompt: "For how long?",
userInput: "Duration",
},
degreeForm: {
prompt: "What was your degree?",
userInput: "Degree",
},
majorForm: {
prompt: "What did you study?",
userInput: "Major",
},
}
export default class NewEducation extends React.Component {
constructor(props) {
super(props);
this.state = {
//form: states.reviewForm,
form: states.schoolForm,
userInputs: {
schoolName: "",
duration: "",
degree: "",
major: "",
GPA: "",
coursework: "",
},
//for testing
userInputValue: "",
}
}
答
你placeholder={this.state.form.userInput}
指的是不同的值,更新的状态onChangeText={(userInputValue) => this.setState({userInputValue})}
试试这个this.setState({form: { ...this.state.form, userInput: userInputValue }})}
你的函数现在应该是这样的:
<TextInput
style={[styles.textContentWhite, styles.textContentWhiteHeight, styles.indentLeft]}
placeholder={this.state.form.userInput}
placeholderTextColor="#B7BEDE"
onChangeText={(userInputValue) =>
this.setState({form: { ...this.state.form, userInput: userInputValue }})}
/>
我刚刚尝试过你的建议和textInput一旦我开始输入消失,在控制台中没有错误信息... – bleepmeh
你的状态对象是怎样的?基于您的占位符代码,它似乎有这样的属性:form:{userInput:''}在这种情况下,它应该工作,因为我刚测试它 – linasmnew
您好我张贴我的状态对象上面 – bleepmeh