如何管理保存在 reactjs 状态中的数组



这是我在那里的第一篇文章:)

那么如何管理保存在 reactjs 状态的数组呢?

背景:我反应的一个网站,它为学生提供多项选择题,由老师管理,一个学术案例

{
"id": 0,
"textvalue": "Les licornes existent-elles ?",
"singlecorrectanswer": true,
"explication": "hyhy-bèikb_b",
"answer": [
{
"id": 1,
"author": 1,
"textanswer": "Evidemment, oui",
"correct": true
},
{
"id": 2,
"author": 1,
"textanswer": "Bien sur que non",
"correct": false
}
]
}

目前,我将其作为问题输入的属性value: this.state.question.text value但是我无法通过输入文本来修改字段,可能是因为未定义 onChange。

此外,我希望用户能够修改每个答案。 对于答案,这是相同的问题: 我将在我的"答案"上实现一个映射,一个解决方案是创建一个 onChange 函数,该函数将处理映射的索引和状态的数组并对其进行修改。但是这个解决方案有点丑陋。您是否有更好的解决方案来自动将字段的"值"绑定到状态?

我很抱歉我的英语,我是法国人

谢谢

你真的应该提供我们可以审查的代码。

是的,您的问题可能是因为您没有提供 onChange 事件。 这是在文档中 https://reactjs.org/docs/forms.html#controlled-components

我在这里测试了这个: https://codesandbox.io/s/nervous-ives-ccy4u

我找到了一个解决方案,但这不是最好的。正如jasdhfiu所说,我必须提供一个onChange事件

这是我的代码

handleQuestionChange = (field, value) => {
let question = Object.assign({}, this.state.question);
question[field] = value;
this.setState({question}, () => this.updateError());
};
handleQuestionThemeChange = (value) => {
let question = Object.assign({}, this.state.question);
question.theme = this.state.themes.find(o => o.label === value);
this.setState({question}, () => this.updateError());
};
handleAnswerChange = (field, value, index) => {
let question = Object.assign({}, this.state.question);
question.answer[index][field] = value;
this.setState({question}, () => this.updateError());
};

我的事件放在按钮上:

onChange: (e) => this.handleQuestionChange('textvalue', e.target.value)
onChange: (e) => this.handleQuestionChange('explication', e.target.value)
onClick={() => this.handleAnswerChange('correct', !answer.correct, index)
onChange: e => this.handleAnswerChange('textanswer', e.target.value, index)
onChange={e => this.handleQuestionThemeChange(e.target.value)}

如果有更简单的方法让我知道 谢谢

我建议您使用 onBlur 而不是 onChange,这样您就不需要在每次字符更改时更新状态。 要使用onBlur,您需要使用默认值而不是值。

<input defaultValue={this.state.question.text value} onBlur={e => updateValue(e.target.value) /* your update function */} type='text' />

最新更新