【问题标题】:How to read field input into a react state array?如何将字段输入读入反应状态数组?
【发布时间】:2021-01-05 21:10:03
【问题描述】:

在我正在开发的网络应用程序中,我让用户可以选择他们在设施内拥有的机器数量。基于所选数字,向用户显示相应数量的表单域。我设法使用这个问题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"));

【问题讨论】:

    标签: javascript arrays reactjs react-state


    【解决方案1】:

    一种选择是将状态中的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 数组。这可能不是您的用例所关心的问题,但如果是,那么数组可能不是是最好的解决方案。如果每个元素都有某种唯一标识符,则可以使用对象结构。

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2021-10-17
      相关资源
      最近更新 更多