如何使用 Ant Design 创建问卷类型的表单? [英] How to create a questionnaire type form using Ant Design?

查看:72
本文介绍了如何使用 Ant Design 创建问卷类型的表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ant Design 提供了一个动态表单项,通过使用它,我可以添加和删除多个字段.但现在我想在其中进行嵌套,即我想创建一个类似于表单的问卷,我想在其中添加多个问题及其各自的答案.

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
    });
  };

在codesandbox.io上创建了一个演示.

推荐答案

问题不在于函数,而在于 getFieldDecorator:

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:添加了完整代码 - 沙盒尝试

UPD: Added the full code - Sandbox try

这篇关于如何使用 Ant Design 创建问卷类型的表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆