How to create a questionnaire type form using Ant Design?

核能气质少年 提交于 2019-12-02 03:51:28

问题


Ant Design provides a Dynamic Form Item, by using that, I can add and remove multiple fields. But now I want do nesting in that, i.e., I want to create a questionnaire like form in which I want to add multiple questions and their respective answers.

Currently, when I am adding questions, its working correct but when I am adding answer to one question, its also adding to the all questions.

The functions of adding and removing questions and answers are as given below:

remove = k => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    // We need at least one passenger
    if (keys.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys.filter(key => key !== k)
    });
  };

  add = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys = form.getFieldValue("keys");
    const nextKeys = keys.concat(uuid);
    uuid++;
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys: nextKeys
    });
  };

  remove1 = k1 => {
    const { form } = this.props;
    // can use data-binding to get
    const keys1 = form.getFieldValue("keys1");
    // We need at least one passenger
    if (keys1.length === 1) {
      return;
    }

    // can use data-binding to set
    form.setFieldsValue({
      keys: keys1.filter(key1 => key1 !== k1)
    });
  };

  add1 = () => {
    const { form } = this.props;
    // can use data-binding to get
    const keys1 = form.getFieldValue("keys1");
    const nextKeys1 = keys1.concat(uuid1);
    uuid1++;
    // can use data-binding to set
    // important! notify form to detect changes
    form.setFieldsValue({
      keys1: nextKeys1
    });
  };

I have created a demo on codesandbox.io.


回答1:


The problem is not in the functions but in getFieldDecorator:

<FormItem>
     {getFieldDecorator(`answer[${k}]`, {
         validate: [
         ...
         ]
         })(<Input type="" placeholder=" Enter Answer" />)

You submit the same input value for all inputs.

Without the decorator it works fine and you can put validation to your custom function and call it

 <FormItem>
     <Input 
         type="" 
         placeholder=" Enter Answer" 
         // value={this.state.answer}
         // onChange={e => this.handleChange(e)} 
      />
 </FormItem>

UPD: Added the full code - Sandbox try



来源:https://stackoverflow.com/questions/51782379/how-to-create-a-questionnaire-type-form-using-ant-design

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!