美文网首页
ant design form组件简单封装与使用

ant design form组件简单封装与使用

作者: ticktackkk | 来源:发表于2021-03-02 02:18 被阅读0次

    封装

    import React, { useEffect, useState } from "react";
    import { Button, Form, Input, Select, InputNumber, Radio, Modal, Checkbox, DatePicker, Switch } from "antd";
    import { Uploader } from "react-single-app";
    const { Option } = Select;
    const { TextArea } = Input;
    function NewModal({ formItem, title, visible, onCancel, onOk, rowValue, formItemLayout }) {
        const [form] = Form.useForm();
        useEffect(() => {
            form.resetFields();
            rowValue && form.setFieldsValue({ ...rowValue });
        }, [visible])
        function initFromItem() {
            if (!formItem || formItem.length === 0) return false;
            const fromList = [];
            formItem.map((item) => {
                switch (item.type) {
                    case "Text":
                        fromList.push(TextEle(item));
                        break;
                    case "Input":
                        fromList.push(InputEle(item));
                        break;
                    case "Select":
                        fromList.push(SelectEle(item));
                        break;
                    case "InputNumber":
                        fromList.push(InputNumberEle(item));
                        break;
                    case "Radio":
                        fromList.push(RadioEle(item));
                        break;
                    case "TextArea":
                        fromList.push(TextAreaEle(item));
                        break;
                    case "CheckBox":
                        fromList.push(CheckboxEle(item));
                        break;
                    case "Date":
                        fromList.push(DateEle(item));
                        break;
                    case "Switch":
                        fromList.push(SwitchEle(item));
                        break;
                    case "Uploder":
                        fromList.push(UploderEle(item));
                        break;
                }
            });
            return fromList;
        }
        //rules 验证
        function rulesEle(item) {
            let rules = [];
            let messages = `${item.label}不能为空`;
            let type = ["Select", "Radio"];
            if (type.includes(item.type)) {
                messages = `请选择${item.label}`;
            }
            if (item.required) {
                let message = item.message || messages;
                rules.push({ required: true, message });
            }
            if (item.rules && item.rules.length > 0) {
                rules = rules.concat(item.rules);
            }
            return rules;
        }
        //test
        function TextEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    {item.text}
                </Form.Item>
            );
        }
    
        //input
        function InputEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Input
                        placeholder={item.placeholder}
                    />
                </Form.Item>
            );
        }
    
        //   select
        function SelectEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Select
                        style={{ width: '100%' }}
                        placeholder={item.placeholder}
                        optionFilterProp="children"
                        showSearch
                        allowClear
                    >
                        {item.option &&
                            item.option.map((ite, index) => {
                                return (
                                    <Option value={ite.name} key={ite.id}>
                                        {ite.id}
                                    </Option>
                                );
                            })}
                    </Select>
                </Form.Item>
            );
        }
        //   InputNumber
        function InputNumberEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <InputNumber
                        style={{ width: '100%' }}
                    />
                </Form.Item>
            );
        }
    
        //Radio
        function RadioEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Radio.Group defaultChecked>
                        {item.option &&
                            item.option.map((ite, index) => {
                                return <Radio value={ite.name}key={ite.id}>{ite.id}</Radio>;
                            })}
                    </Radio.Group>
                </Form.Item>
            );
        }
        //  TextArea
        function TextAreaEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Input.TextArea />
                </Form.Item>
            );
        }
        // CheckBox
        function CheckboxEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Checkbox.Group options={item.option} />
                </Form.Item>
            );
    
        }
        // Date
        function DateEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                </Form.Item>
            );
        }
        //Switch
        function SwitchEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    rules={rules}
                >
                    <Switch />
                </Form.Item>
            );
        }
        //Uploder
        function UploderEle(item) {
            const rules = rulesEle(item);
            return (
                <Form.Item
                    label={item.label}
                    name={item.name}
                    key={item.name}
                    extra={item.extra}
                    rules={rules}
                >
                    <Uploader
                        style={{ width: 100, height: 100 }}
                        allowTypes={item.Types}
                        onChange={src=>{
                            src ? modalForm.setFieldsValue({ [item.name]: src.src }) : modalForm.setFieldsValue({ [item.name]: null })
                        }}
                    />
                </Form.Item>
            )
    
        }
    
        // 提交表单
        function Submit() {
            // console.log(props);
            form.validateFields().then((values) => {
                onOk(values);
            });
        }
    
        let formLayout = formItemLayout || {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        };
    
        return (
            <div>
                <Modal
                    title={title}
                    visible={visible}
                    onCancel={onCancel}
                    onOk={Submit}
                    maskClosable={false}
                    destroyOnClose={true}
                    getContainer={false}
                    width={700}
                >
                    <Form form={form} {...formLayout}  >
                        {initFromItem()}
                    </Form>
                </Modal>
            </div >
        );
    }
    
    export default NewModal;
    

    使用

    import React, { useEffect, useState } from "react";
    import NewModal "./components/NewModal";
    
    function App() {
     const [deValue, setDevalue] = useState({
            title: 123,
            visible: false,
            rowValue:''
        })
      const [visible, setVisible] = useState(true);
    
     function getOptions() {
            formItem.map(item => {
                if (item.request && !item.option.length) {
                    lib.request({
                        url: item.request,
                        needMask: false,
                        data: item.data,
                        success: res => {
                            console.log(res);
                            item.option = res || []
                            setFormItem(formItem)
                        }
                    })
                }
            })
            return formItem;
        }
    const [formItem, setFormItem] = useState([
            {
                type: "Input",
                label: "你好",
                name: "a",
                width: "200px",
                placeholder: "aaaaaa",
                required: true,
                rules: [
                    { required: true, message: "bitian" },
                    { max: 5, message: "5" },
                    ({ getFieldValue }) => {
                        // console.log(getFieldValue("aaa"));
                        return Promise.resolve();
                    },
                ],
            },
            {
                type: "Select",
                label: "中文",
                name: "b",
                required: true,
                width: "200px",
                placeholder: "请选择语言",
                request: "/account-web/....",
                data: { },
                option: [ ],
            },
            {
                type: "InputNumber",
                label: "中文",
                name: "c",
                required: true,
                width: "200px",
                rules: [],
            },
            {
                type: "Radio",
                label: "kbdsfj",
                name: "d",
                required: true,
                width: "200px",
                option: [
    
                ],
            },
            {
                type: "TextArea",
                label: "中文",
                name: "e",
                required: true,
                width: "200px",
                rules: [],
            },
        ])
    
      //提交表单,关闭Modal
     function onOk(props) {
            console.log(props, 1);
            setDevalue({ ...deValue, visible: false });
        }
        function onCancel(props) {
            setDevalue({ ...deValue, visible: false });
        }
        let rowValue = {
            'a': '123',
            c: 123,
            d: 'aa',
            e: 123
        }
    
        let Myprops = {
            title: deValue.title,
            visible: deValue.visible,
            formItem: getOptions(),
            rowValue:deValue.rowValue
            onCancel,
            onOk
        }
      return (
        <div>
          <NewModal {...Myprops} />
        </div>
      );
    }
    
    export default App;
    
    

    相关文章

      网友评论

          本文标题:ant design form组件简单封装与使用

          本文链接:https://www.haomeiwen.com/subject/bfttqltx.html