react+antd系列之Form表单(1):添加与删除

在用antd的时候,我们如果要对表单进行添加和删除该怎么弄呢,如下:

import { connect } from 'dva';
import { Form, Input, Button } from 'antd';
import styles from './eg1.css';

const FormItem = Form.Item;

function Page(props) {
  const { form } = props;
  const { getFieldDecorator, getFieldValue } = form

  // 表单提交
  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        console.log(values);
      }
    });

  }

  // 添加
  const add = () => {
    const list = form.getFieldValue('list');
    const nextList = list.concat({});
    form.setFieldsValue({
      list: nextList,
    });


  }

  // 删除
  const deleteRow = (index) => {
    const list = form.getFieldValue('list');
    const content = form.getFieldValue('content');

    if (list.length === 1) {
      return;
    }

    form.setFieldsValue({
      list: list.filter((item, key) => key !== index),
      content: content.filter((item, key) => key !== index),
    });



  }

  getFieldDecorator('list', { initialValue: [{}] });
  const list = getFieldValue('list');

  const listContent = list.map((item, index) => {
    return (
      <FormItem label='名称:' key={index}>
      {getFieldDecorator(`content[${index}].name`, {
         rules: [{
         required: true,
         message: "名称不能为空!",
         }],
      })(
         <Input placeholder="请输入名称" style={{ width: '60%', marginRight: 8 }} />
      )}

       {index > 0 ? (
           <Button type="primary" onClick={deleteRow.bind(this, index)}>删除</Button>
       ) : null}


      </FormItem>
    );
  });


  return (
    <div className={styles.normal}>
        <Form onSubmit={handleSubmit}>

        {listContent}
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
          <Button type="primary" style={{ marginLeft: '10px' }} onClick={add}>增加</Button>
        </FormItem>
      </Form>

    </div>
  );
}


const page = Form.create()(Page);
export default connect()(page);

这里不仅能对表单进行增加和删除,还能对表单进行验证,看是否有输入,以上是本身没有数据的情况,如果是有数据的情况如下:

import React from 'react';
import { connect } from 'dva';
import { Form, Input, Button } from 'antd';
import styles from './eg2.css';

const FormItem = Form.Item;

function Page(props) {
  const { form } = props;
  const { getFieldDecorator, getFieldValue } = form

  // 表单提交
  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        console.log(values);
      }
    });

  }

  // 添加
  const add = () => {
    const list = form.getFieldValue('list');
    const nextList = list.concat({});
    form.setFieldsValue({
      list: nextList,
    });


  }

  // 删除
  const deleteRow = (index) => {
    const list = form.getFieldValue('list');
    const content = form.getFieldValue('content');

    if (list.length === 1) {
      return;
    }

    form.setFieldsValue({
      list: list.filter((item, key) => key !== index),
      content: content.filter((item, key) => key !== index),
    });



  }


  const slist = [{
    id:'0001',
    name: '黎明'
  }, {
    id:'0002',
    name: '晴天'
  }]
  getFieldDecorator('list', { initialValue: slist });
  const list = getFieldValue('list');

  const listContent = list.map((item, index) => {
    getFieldDecorator(`content[${index}].id`, {initialValue: item.id || ''})
    return (
      <FormItem label='名称:' key={index}>
      {getFieldDecorator(`content[${index}].name`, {
         rules: [{
         required: true,
         message: "名称不能为空!",
         }],
         initialValue: item.name || ''
      })(
         <Input placeholder="请输入名称" style={{ width: '60%', marginRight: 8 }} />
      )}

       {index > 0 ? (
           <Button type="primary" onClick={deleteRow.bind(this, index)}>删除</Button>
       ) : null}


      </FormItem>
    );
  });


  return (
    <div className={styles.normal}>
        <Form onSubmit={handleSubmit}>

        {listContent}
        <FormItem>
          <Button type="primary" htmlType="submit">提交</Button>
          <Button type="primary" style={{ marginLeft: '10px' }} onClick={add}>增加</Button>
        </FormItem>
      </Form>

    </div>
  );
}


const page = Form.create()(Page);
export default connect()(page);

一般如果本身有数据,都会有每行数据的id,但是这个id不显示,我们都会用getFieldDecorator给id声明,这样在我们提交表单的时候,就可以得到表单抓取到id的数据,有数据跟没有数据的差别就是,有数据需要在表单getFieldDecorator的时候给一个初始值,其他两者都一样

具体代码下载地址:https://gitee.com/hope93/antd-form1

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
React中,清空表单可以通过Antd的Form组件提供的`resetFields`方法来实现。具体步骤如下: 1. 在表单的父组件中引入`Form`组件,并将表单的所有控件都用`Form.Item`包裹起来,每个`Form.Item`需要设置`name`属性,这个属性值需要与`getFieldDecorator`方法中的`id`参数保持一致。 ```jsx import { Form, Input, Button } from 'antd'; class MyForm extends React.Component { render() { const { getFieldDecorator } = this.props.form; return ( <Form> <Form.Item label="用户名" name="username"> {getFieldDecorator('username')(<Input />)} </Form.Item> <Form.Item label="密码" name="password"> {getFieldDecorator('password')(<Input.Password />)} </Form.Item> <Form.Item> <Button type="primary" onClick={this.handleSubmit}>提交</Button> <Button onClick={this.handleReset}>重置</Button> </Form.Item> </Form> ); } } ``` 2. 在表单的父组件中定义`handleSubmit`和`handleReset`方法。`handleSubmit`方法用于提交表单,`handleReset`方法用于清空表单。 ```jsx class MyForm extends React.Component { handleSubmit = e => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { console.log('Received values of form: ', values); } }); }; handleReset = () => { this.props.form.resetFields(); }; render() { //... } } ``` 3. 在表单的父组件中将`MyForm`组件包裹在`Form.create`函数中,生成一个新的高阶组件,并将其导出。 ```jsx const WrappedMyForm = Form.create({ name: 'my_form' })(MyForm); export default WrappedMyForm; ``` 这样,当用户点击表单中的“重置”按钮时,表单中的所有控件都会被清空。如果想要清空表单中的某一个控件,可以通过`setFieldsValue`方法来清空,具体可见前面的回答。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值