如何创建可以从 React js 中的状态更改的动态表单?

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

我想创建一个表单,在其中可以添加和删除字段以及编辑 React js 状态中的值。我正在使用

react-bootstrap

javascript reactjs
2个回答
2
投票

尝试使用

reactjs-form-builder
这是有状态的表单生成器,这意味着您可以使用状态来管理表单,如下例所示。查看此链接https://www.npmjs.com/package/reactjs-form-builder

import React, { Component } from 'react'

import FormBuilder from 'reactjs-form-builder'

class Example extends Component {
  constructor(props) {
    super(props);
    this.setState({
      form:{
        "fields":{
          "name":{
            'label': "Product Name",
            "type": "text",
            "placeholder": true,
            "required": true,
            "requireMessage": "This Field is Required" // To customize message if field is empty
          },
          "description":{
            'label': "Product Name",
            "type": "textarea",
            "required": true,
          },
          "categories": {
             'label': "Categories",
              "type": "select",
              'options': [
                {'label':"Apple", 'value':1},
                {'label':"Banana", 'value':2}
              ],
              "placeholder": true,
              "required": true,
              "requireMessage": "This Field is Required"
         },
         'submit': {
            "type": "submit",
            "label": "Create Product",
            'color:': 'btn-primary',
          }
        }
      }
    });
  }
  onChange(data){
    this.setState({
      form: data
    });
  }
  onSubmit(data){
    this.setState({
      form: data
    });
    var name = this.state.form.name.value;
    var description = this.state.form.description.value;
    var category = this.state.form.category.value; 
  }
  render() {
    return <FormBuilder
      fields={this.state.form}
      onChange={this.onChange.bind(this)}
      onSubmit={this.onSubmit.bind(this)}
    />
  }
}

0
投票

您可以使用blitz表单生成器,它非常高效,可以立即完成工作

© www.soinside.com 2019 - 2024. All rights reserved.