从JSON生成React表单字段

时间:2019-05-16 12:15:15

标签: reactjs material-ui

我正在尝试从JSON配置生成表单。我正在解析JSON,并使用地图函数生成实质性的UI TextField组件。 但是问题在于生成的组件无法渲染,而是整个JS代码出现在屏幕上。不知道为什么。

这是我在2个文件中的代码:

FormConfig.js:


  "Form1": {   
    "fields": [
      {
        uiElement: "TextField",
        id: '"standard-name"',
        name: "'asdada'",
        className: "{classes.textField}",
        value: "{this.state.name}",
        onChange: '{this.handleChange("name")}',
        required: true,
        margin: '"normal"'
      },
      {
        uiElement: "TextField",
        id: '"standard-uncontrolled"',
        name: '"asda"',
        label: '"Required"',
        className: '"{classes.textField}"',
        value: '"asd"',
        onChange: "{}",
        required: true,
        margin: '"normal"'
      }
   ]
  },
  "OtherForm":
  {
      "fields": [{}, {}]
  }
}

const getForm = formName => {
  return FormConfig[formName].fields.map(field => `<${field.uiElement} `+
    Object.keys(field).filter(k => k !== 'uiElement')
      .map(k => {
        return k + "=" + field[k];
      })
      .join(" ") + `/>`
  )
}

export default getForm;

TestForm.js

class TextFields extends React.Component {
  state = {
    name: 'Cat in the Hat',
    age: '',
    multiline: 'Controlled',
    currency: 'EUR',
  };

  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
  };

  render() {
    const { classes } = this.props;

    return (
      <form className={classes.container} noValidate autoComplete="off">

        {
            getForm("Form1")
        }

        <TextField
          required
          id="standard-required"
          label="Required"
          defaultValue="Hello World"
          className={classes.textField}
          margin="normal"
        />

我原以为对getForm()的调用会呈现我的字段,但是它会在网页上吐出来。我在做错什么吗?

<TextField id="standard-name" name='asdada' className={classes.textField} value={this.state.name} onChange={this.handleChange("name")} required=true margin="normal"/><TextField id="standard-uncontrolled" name="asda" label="Required" className="{classes.textField}" value="asd" onChange={} required=true margin="normal"/><TextField id="standard-read-only-input" name="asd" label="Read Only" className={classes.textField} value="asd" onChange={} required=false margin="normal" InputProps={{readOnly: true}}/><TextField id="standard-dense" name="w3rg" label="Dense" className={classNames(classes.textField, classes.dense)} value="sdas" onChange={} required=false margin="dense"/>

1 个答案:

答案 0 :(得分:1)

尝试在映射时返回组件:

const getForm = formName => {
  return FormConfig[formName].fields.map(field => evalComponent(field))
}

const evalComponent = field => {
    let { uiElement, ...props } = field
    switch(uiElement) {
        case 'TextField':
            return <TextField {...props}/>
        default:
            return false
    }
}