简体   繁体   English

如何创建动态 forms 可以从反应 js 中的 state 更改?

[英]How do I create dynamic forms which can be changed from state in react js?

I want to create form in which I can add and delete fields and edit values from state of react js.我想创建一个表单,我可以在其中添加和删除字段并编辑来自 react js 的 state 的值。 I am using react-bootstrap .我正在使用react-bootstrap

Try using reactjs-form-builder this is stateful form builder which means you can manage form using state like in example below.尝试使用reactjs-form-builder这是有状态的表单构建器,这意味着您可以使用 state 管理表单,如下例所示。 check out this link https://www.npmjs.com/package/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)}
    />
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM