如何将字段输入读取到反应状态数组中



在我正在开发的web应用程序中,我为用户提供了一个选项,可以选择他们在设施中拥有的机器数量。根据所选数字,用户将看到相应数量的表单字段。我在这里用这个问题配置了界面。我现在很困惑如何将每个字段的输入值读取到动态数组中?这是我目前正在编写的代码JSFiddle。

handleOnChange(value) {
this.setState({ inputSize: value.target.value });
}
renderInputs(value) {
const inputs = [];
for (let i = 0; i < value; i++) {
inputs.push(
<div>
<Input
value={this.state.sortingMachines[i]}
onChange={(event) =>
this.props.setState({ sortingMachines: event.target.value })
}
icon="ethereum"
/>
</div>
);
for (let i = 0; i < value; i++) {
console.log(this.state.sortingMachines[i]);
}
}
return inputs;
}
render() {
const { sortingMachines } = this.state;
console.log(this.state.inputSize);
return (
<div>
<Form.Field width={6}>
<label>Sorting Machines Address</label>
<input
type="number"
name="quantity"
min="1"
max="7"
onChange={(value) => this.handleOnChange(value)}
/>
<div>{this.renderInputs(this.state.inputSize)}</div>
</Form.Field>
</div>
);
}
ReactDOM.render(<Hello name="World" />, document.getElementById("container"));

一个选项是将处于状态的sortingMachines数组默认为空数组,然后确保在更改处理程序中将ith元素设置为所需的值(复制数组后(;

constructor() {
this.state  = {
sortingMachines: []
}
}
renderInputs(value) {
const inputs = [];
for (let i = 0; i < value; i++) {
inputs.push(
<div>
<Input
value={this.state.sortingMachines[i]}
onChange={(event) =>
const newSortingMachines = [...this.state.sortingMachines];
newSortingMachines[i] = event.target.value;
this.setState({ sortingMachines: newSortingMachines })
}
icon="ethereum"
/>
</div>
);
for (let i = 0; i < value; i++) {
console.log(this.state.sortingMachines[i]);
}
}
return inputs;
}

现在,每个元素的sortingMachine值将位于其相应的数组位置。

编辑:这里需要注意的一点是,如果删除某个元素,则需要确保相应地移动sortingMachines数组。这可能不是您的用例所关心的问题,但如果是,那么数组可能不是最佳解决方案。如果每个元素都有某种唯一的标识符,那么可以使用对象结构。

最新更新