Antd知识点总结(二)

Antd知识点总结

一、关于封装Form表单控件元素

有时候Antd原生提供的表单组件如:Input, Button, Checkbox不能满足业务需要,需进行进一步的封装。

import React, { useState, useEffect, Children } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Checkbox } from "antd";
const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 8
  }
};
const formTailLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 8,
    offset: 4
  }
};

const WrapperItem = (props) => {
  const { value, onChange, children } = props;
  // React.cloneElement(children, { value, onChange });
  return (
    <div
      style={{ width: 300, height: 200, backgroundColor: "pink" }}
      className="wrapper-item"
    >
      {/* <Input value={value} onChange={onChange} /> */}
      {React.cloneElement(children, { value, onChange })}
    </div>
  );
};

const DynamicRule = () => {
  const [form] = Form.useForm();
  const [checkNick, setCheckNick] = useState(false);
  useEffect(() => {
    form.validateFields(["nickname"]);
  }, [checkNick]);

  const onCheckboxChange = (e) => {
    setCheckNick(e.target.checked);
  };

  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      console.log("Success:", values);
      const vs = form.getFieldsValue();
      console.log(vs);
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  return (
    <Form form={form} name="dynamic_rule">
      <Form.Item
        {...formItemLayout}
        name="username"
        label="Name"
        rules={[
          {
            required: true,
            message: "Please input your name"
          }
        ]}
      >
        <Input placeholder="Please input your name" />
      </Form.Item>
      <Form.Item
        {...formItemLayout}
        name="nickname"
        label="Nickname"
        rules={[
          {
            required: checkNick,
            message: "Please input your nickname"
          }
        ]}
      >
        <Input placeholder="Please input your nickname" />
      </Form.Item>
      <Form.Item {...formTailLayout}>
        <Checkbox checked={checkNick} onChange={onCheckboxChange}>
          Nickname is required
        </Checkbox>
      </Form.Item>
      <Form.Item {...formTailLayout}>
        <Button type="primary" onClick={onCheck}>
          Check
        </Button>
      </Form.Item>
      <Form.Item name="s" {...formTailLayout}>
        <WrapperItem>
          <Input />
        </WrapperItem>
      </Form.Item>
    </Form>
  );
};

ReactDOM.render(<DynamicRule />, document.getElementById("container"));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值