React 将输入值设置为状态数组中的值
React Setting input value to value in a state array
我有一个 React-Bootstrap FormControl
并且我正在尝试使用以下设置状态:
<FormGroup controlId={0} key={0} >
<FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
</FormGroup>
This.state.form_answers 在构造函数中设置如下:
this.state = ({
form_answers : ['foo','bar','foo-bar'],
});
我的句柄更改函数正在使用以下内容更新状态:
handleChange(event) {
let form_answers = this.state.form_answers;
form_answers[parseInt(event.target.id)] = event.target.value;
this.setState({
form_answers : form_answers,
});
}
状态正在正确更新,但输入字段上显示的值根本没有改变。我还收到以下错误消息:
warning.js:36 Warning: FormControl is changing an uncontrolled input
of type undefined to be controlled. Input elements should not switch
from uncontrolled to controlled (or vice versa). Decide between using
a controlled or uncontrolled input element for the lifetime of the
component.
当我将 FormControl
设置为以下时,它起作用了:
<FormGroup controlId={0} key={0} >
<FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
</FormGroup>
handleChange(event) {
this.setState({
my_test_state: event.target.value,
});
}
但是,由于我正在动态创建多个 FormControl 元素,因此工作解决方案不可行。不能将输入值设置为状态索引值吗?如果不可能,那么有人可以就如何最好地为动态创建的输入字段提供 update/set 值的建议。
The state is being updated correctly, but the value displayed on the input field is not changing at all
你确定吗?我做了一个本地测试,状态没有正确更新,因为 controlId
是 FormGroup
的 属性 而不是 FormControl
。也就是说,FormControl
将继承其 id
的 controlId
值(如果未设置)。
当我在 FormControl
中将 controlId
切换为 id
时,它按预期工作。
我有一个 React-Bootstrap FormControl
并且我正在尝试使用以下设置状态:
<FormGroup controlId={0} key={0} >
<FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
</FormGroup>
This.state.form_answers 在构造函数中设置如下:
this.state = ({
form_answers : ['foo','bar','foo-bar'],
});
我的句柄更改函数正在使用以下内容更新状态:
handleChange(event) {
let form_answers = this.state.form_answers;
form_answers[parseInt(event.target.id)] = event.target.value;
this.setState({
form_answers : form_answers,
});
}
状态正在正确更新,但输入字段上显示的值根本没有改变。我还收到以下错误消息:
warning.js:36 Warning: FormControl is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
当我将 FormControl
设置为以下时,它起作用了:
<FormGroup controlId={0} key={0} >
<FormControl onChange={this.handleChange} value={this.state.form_answers[0]} />
</FormGroup>
handleChange(event) {
this.setState({
my_test_state: event.target.value,
});
}
但是,由于我正在动态创建多个 FormControl 元素,因此工作解决方案不可行。不能将输入值设置为状态索引值吗?如果不可能,那么有人可以就如何最好地为动态创建的输入字段提供 update/set 值的建议。
The state is being updated correctly, but the value displayed on the input field is not changing at all
你确定吗?我做了一个本地测试,状态没有正确更新,因为 controlId
是 FormGroup
的 属性 而不是 FormControl
。也就是说,FormControl
将继承其 id
的 controlId
值(如果未设置)。
当我在 FormControl
中将 controlId
切换为 id
时,它按预期工作。