在 onChangeText 函数中更新数组散列的 TextInput 值

Update TextInput value of hash of array in onChangeText function

  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: "helloas fast" percentage: 0}

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

提前致谢。

你没有很好地处理数组数据。您可以保留其结构,也可以使用 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)
            ]
          });
        }} 
 />