如何在表单中正确显示值?

问题描述 投票:0回答:2

我正在尝试从我所处的状态中生成一个from:

const { id } = this.props.match.params;
const formGen = this.state.arr.map(arr => {
  if (id == arr.id) {
    const inner = this.state.arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));
  }
});

现在,我不知道如何让它显示在渲染选项卡中,因为我在变量中有一个变量:

<form />
        {formGen.inner}
      </div>

这是我想要映射的状态

 arr: [
      {
        id: 1,
        name: 'firstForm',
        input: [
          {
            inputLabel: 'wowLabel',
            inputType: 'wowType',
            inputValue: 'wowValue'
          },
          {
            inputLabel: 'wowLabel2',
            inputType: 'wowType2',
            inputValue: 'wowValue2'
          }
        ]
      }
arrays reactjs forms
2个回答
0
投票

您可以返回它,而不是将响应存储在变量中,否则返回undefined,然后过滤掉响应。

const { id } = this.props.match.params;
const formGen = this.state.arr.map(arr => {
  if (id == arr.id) {
    return this.state.arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));
  }
  return;
}).filter(Boolean);

在此之后,你可以渲染它

 <form />
    {formGen}
  </div>

0
投票

const { id } = this.props.match.params;

// replace the first map with a find
const arr = this.state.arr.find(a => a.id == id);

// if arr is defined
if(arr){
    const inner = arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));

} else {
  // indicate to the user the that id was not found and what to do to fix the problem
}

<form>{inner}</form>
© www.soinside.com 2019 - 2024. All rights reserved.