更新onChangeText函数

时间:2017-12-21 09:25:02

标签: javascript arrays reactjs react-native textinput

  constructor(props) {
   super(props);
    this.state = {
     answers: props.element.answers_data.map((answer, index) => {
     return answer;
    }
  })

     <TextInput
      value = {this.state.answers[index].answer_text}
     onChangeText={(answer_text) => {
              this.setState({
                answers: [
                    ...this.state.answers.slice(0, index),
                    {answer: {answer_text}},
                    ...this.state.answers.slice(index + 1, 
                    this.state.answers.length)
                ]
              });
            }} 
       />

我的答案数据结构是 like = 0:{id:799,answer_text:&#34; helloas fast&#34;百分比:0}

我想更新答案文本并将其存储在this.state.answers中,但是当我在textinput上写文本并更新它时,我只得到hash中的answer_text,我想要所有id,answer_text,哈希百分比。 所以,我需要建议。

提前致谢。

1 个答案:

答案 0 :(得分:2)

您没有很好地处理数组数据。您可以保留其结构,也可以使用answers_data.map将它们转换为字符串。

选项一的完整代码:

constructor(props) {
  super(props);
  this.state = {
    answers: props.element.answers_data.map((answer, index) => {
      return { ...answer };
    })
  }
}

<TextInput
  value = {this.state.answers[index].answer_text}
  onChangeText={(answer_text) => {
          this.setState({
            answers: [
                ...this.state.answers.slice(0, index),
                { ...this.state.answers[index], answer_text },
                ...this.state.answers.slice(index + 1, this.state.answers.length)
            ]
          });
        }} 
 />

选项二的完整代码:

constructor(props) {
  super(props);
  this.state = {
    answers: props.element.answers_data.map((answer, index) => {
      return answer.answer_text;
    })
  }
}

<TextInput
  value = {this.state.answers[index]}
  onChangeText={(answer_text) => {
          this.setState({
            answers: [
                ...this.state.answers.slice(0, index),
                answer_text,
                ...this.state.answers.slice(index + 1, this.state.answers.length)
            ]
          });
        }} 
 />