如何解决如何将字段输入读入反应状态数组?
在我正在开发的网络应用程序中,我为用户提供了一个选项来选择他们在设施内拥有的机器数量。根据选择的数量,向用户显示相应数量的表单域。我设法使用这个问题 here 配置了界面。我现在对如何将每个字段的输入值读入动态数组感到困惑? 这是我目前正在处理的代码 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
数组。这可能不是您的用例的问题,但如果是,那么数组可能不是是最好的解决方案。如果每个元素都有某种唯一标识符,则可以使用对象结构。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。