当状态发生变化时,textInput不会重新渲染

时间:2017-10-04 20:36:47

标签: react-native

我目前有这个函数,它为每个状态呈现一个带有不同占位符的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: "",
    }
  }

1 个答案:

答案 0 :(得分:0)

您的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 }} )}
  />