如何通过传递对象来初始化表单输入值?

时间:2016-09-15 00:08:27

标签: formsy-react

我正在尝试使用formsy-react创建一个编辑表单。有没有办法使用对象来初始化formy-react中的表单输入值,而不是手动执行<Formsy.Form className="horizontal" onValidSubmit={this._handleSubmit.bind(this)}> <fieldset> <legend>Product Details</legend> <Input name="name" label="Name" type="text" required /> <Input name="sku" label="SKU" type="text" required /> </fieldset> <fieldset> <Row layout='horizontal'> <input className="btn btn-primary" formNoValidate={true} type="submit" defaultValue="Submit" /> &nbsp; <button className="btn btn-default" onClick={this._handleCancel.bind(this)}>Cancel</button> </Row> </fieldset> </Formsy.Form>

我的表单代码如下。

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

class Animal {
   private static HashSet house = new HashSet<Class>();
   private static Random random = new Random();

   public Animal() {
       Animal.house.add(getClass());
   }

   public static List party() throws InstantiationException, IllegalAccessException {
       if (house.isEmpty()) {
           return null;
       }

       ArrayList list = new ArrayList<Animal>();
       Class[] classes = (Class[])house.toArray(new Class[0]);
       for(int i = 0; i < 3; i++) {
           list.add(classes[random.nextInt(house.size())].newInstance());
       }
       return list;
   }
}

1 个答案:

答案 0 :(得分:0)

您可以获取Formsy.Form的引用,并使用填充表单的对象调用reset function

import React, { Component } from 'react';
import Formsy from 'formsy-react';
import { Input, Row } from 'formsy-react-components';

class App extends Component {
    componentDidMount() {
        this.handleReset();
    }
    handleReset = () => {
        this.formsyForm.reset({name: 'Widget', sku: 'abc-123'});
    }
    handleSubmit = (formData) => {
        console.log(formData);
    }
    render() {
        return (
          <Formsy.Form ref={(formsyForm) => { this.formsyForm = formsyForm; }} className="horizontal" onSubmit={this.handleSubmit}>
              <fieldset>
                  <legend>Product Details</legend>
                  <Input name="name" label="Name" type="text" value="" required />
                  <Input name="sku" label="SKU" type="text" value="" required />
              </fieldset>
              <fieldset>
                  <Row layout='horizontal'>
                      <input className="btn btn-primary" formNoValidate={true} type="submit" defaultValue="Submit" /> &nbsp;
                      <button className="btn btn-default" type="button" onClick={this.handleReset}>Reset</button>
                  </Row>
              </fieldset>
          </Formsy.Form>
        );
    }
}

export default App;