【问题标题】:Create React Dynamic Forms创建 React 动态表单
【发布时间】:2020-08-05 03:26:51
【问题描述】:

我正在尝试使用 react hooks 和 .map() 实现动态表单;

到目前为止,我已经实现了生成静态表单,如下例所示: https://codesandbox.io/s/material-demo-ndh9q

这是我的静态表格:

<form className={classes.root} noValidate autoComplete="off">
      <Grid container spacing={4}>
        <Grid item xs={12} sm={6} md={4}>
          <TextField id="profile" label="Name" fullWidth={true} />
        </Grid>
        <Grid item xs={12} sm={6} md={4}>
          <TextField id="profile" label="Email" fullWidth={true} />
        </Grid>
        <Grid item xs={12} sm={6} md={4}>
          <TextField id="profile" label="Address" fullWidth={true} />
        </Grid>
        {/* textarea */}
        <Grid item xs={12} sm={12} md={12}>
          <TextField
            label="Info"
            multiline
            rows={1}
            rowsMax={4}
            fullWidth={true}
          />
        </Grid>
      </Grid>
    </form>

在这里我试图使表单动态化:

const initialState = { name: "", email: "", address: "", info: "" };

export default function BasicTextFields() {

const [inputs, setInputs] = useState({ ...initialState });

return(
<form className={classes.root} noValidate autoComplete="off">
      <Grid container spacing={4}>
      {inputs.map((item, index) => (
        <Grid item xs={12} sm={6} md={4}>
          <TextField id={index`${item}`} label={item} fullWidth={true} />
        </Grid>
      )}
  </Grid>
    </form>
)}

但它返回错误,不知道为什么,有人可以帮助我提供详细信息。 请记住,表单的最后一个字段也是一个文本区域,因此获取特定属性。

谢谢!

【问题讨论】:

  • 如果我没记错的话,你的inputs 是一个对象,对吧?

标签: javascript arrays reactjs forms ecmascript-6


【解决方案1】:

我发现您的代码中存在一些问题。

  1. 由于您的inputs 是一个对象,您不能直接在其上使用地图。我使用Object.keys() 来使用map
  2. 您的 template 文字也存在一些问题。

这是您的 form 元素,包含动态内容。

<form className={classes.root} noValidate autoComplete="off">
  <Grid container spacing={4}>
    {
      Object.keys(inputs).map((key, index) => {
        if(key === 'info') {
          return (
            <Grid item xs={12} sm={12} md={12}>
            <TextField
              label={key}
              multiline
              rows={1}
              rowsMax={4}
              fullWidth={true}
            />
            </Grid>
          )
        } else {
          return (
            <Grid item xs={12} sm={6} md={4}>
          <TextField id={`index${key}`} label={key} fullWidth={true} />
        </Grid>
          )
        }
    })
  }
  </Grid>
</form>

这里是codesandbox_link

【讨论】:

  • 如果我有多种类型的字段,我猜每个字段的 if 条件,对吧?谢谢你:)
  • 是的。欢迎:)
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2016-11-11
  • 2015-01-25
  • 2012-05-21
相关资源
最近更新 更多