美文网首页
实现高阶组件版表单组件

实现高阶组件版表单组件

作者: 奔跑的大橙子 | 来源:发表于2023-10-08 10:38 被阅读0次

高阶组件版表单组件设计思路进阶

表单组件要求实现数据收集、校验、提交等特性,可通过高阶组件扩展

高阶组件给表单组件传递一个input组件包装函数接管其输入事件并统一管理表单数据

高阶组件给表单组件传递一个校验函数使其具备数据校验功能

Input.js文件内容如下:

import React, { Component } from 'react'

const Input = (props) => {

    return <input {...props} />

}

export default class CustomizeInput extends Component {

    constructor(props) {

        super(props);

    }

    render() {

        const { value = "", ...otherProps } = this.props;

        return (

            <div style={{padding: '10px'}}>

                <Input style={{outline: 'none'}} value={value} {...otherProps} />

            </div>

        )

    }

}

1.实现一个简单的表单功能:

MyRCForm.js文件内容如下:

import React, { Component } from 'react'

import Input from '../components/Input';

class MyRCForm extends Component {

    constructor(props) {

        super(props);

        this.state = {

            username: "",

            password: ""

        }

    }

    nameChange = (e) => {

        this.setState({

            username: e.target.value

        })

    }

    passwordChange = (e) => {

        this.setState({

            password: e.target.value

        })

    }

    submit = () => {

        const { username, password } = this.state;

        console.log("syta", username, password); // sy-log

    }

    render() {

        const { username, password } = this.state;

        return (

            <div>

                <h3>MyRCForm</h3>

                <Input

                    placeholder="Username"

                    value={username}

                    onChange={this.nameChange}

                />

                <Input

                    placeholder="Password"

                    value={password}

                    onChange={this.passwordChange}

                />

                <button onClick={this.submit}>submit</button>

            </div>

        )

    }

}

export default MyRCForm

2.使用rc-form的高阶组件createForm:

MyRCForm.js文件内容如下:

import React, { Component } from 'react'

import Input from '../components/Input';

import { createForm } from 'rc-form'; // 安装rc-form:npm install rc-form

const nameRules = {required: true, message: "请输入姓名!"};

const passwordRules = {required: true, message: "请输入密码!"};

@createForm()

class MyRCForm extends Component {

    constructor(props) {

        super(props);

    }

    componentDidMount() {

        const { setFieldsValue } = this.props.form;

        setFieldsValue({

            username: "default"

        });

    }

    submit = () => {

        const { getFieldsValue, getFieldValue } = this.props.form;

        console.log("syta", getFieldsValue(), getFieldValue("username")); // sy-log

    }

    render() {

        console.log("props", this.props);

        const { getFieldDecorator } = this.props.form;

        return (

            <div>

                <h3>MyRCForm</h3>

                {getFieldDecorator("username", {rules: [nameRules]})(<Input

                    placeholder="Username"

                />)}

                {getFieldDecorator("password", {rules: [passwordRules]})(<Input

                    placeholder="Password"

                />)}     

                <button onClick={this.submit}>submit</button>

            </div>

        )

    }

}

export default MyRCForm

打印结果如下:

3.自定义一个高阶组件createForm:

MyRCForm.js文件内容如下:

import React, { Component } from 'react';

import Input from '../components/Input';

import { createForm } from '../components/my-rc-form/index';

const nameRules = {required: true, message: "请输入姓名!"};

const passwordRules = {required: true, message: "请输入密码!"};

@createForm

class MyRCForm extends Component {

    constructor(props) {

        super(props);

    }

    componentDidMount() {

        const { setFieldsValue } = this.props.form;

        setFieldsValue({

            username: "李明",

            password: "123"

        });

    }

    submit = () => {

        const { getFieldsValue, getFieldValue, validateFields } = this.props.form;

        console.log("syta", getFieldsValue(), getFieldValue("username")); // sy-log

        validateFields((err, vals) => {

            if(err) {

                console.log("失败", err)

            }else {

                console.log("成功", vals)

            }

        })

    }

    render() {

        console.log("props", this.props);

        const { getFieldDecorator } = this.props.form;

        return (

            <div>

                <h3>MyRCForm</h3>

                {getFieldDecorator("username", {rules: [nameRules]})(<Input

                    placeholder="Username"

                />)}

                {getFieldDecorator("password", {rules: [passwordRules]})(<Input

                    placeholder="Password"

                />)}

                <button onClick={this.submit}>submit</button>

            </div>

        )

    }

}

export default MyRCForm

components/my-rc-form/index.js文件内容如下:

import React, { Component } from 'react'

export function createForm(Cmp) {

    return class extends Component {

        constructor(props) {

            super(props);

            this.state = {}

            this.options = {}

        }

        getFieldsValue = () => {

            return {...this.state};

        }

        getFieldValue = (name) => {

            return this.state[name];

        }

        setFieldsValue = (newStore) => {

            this.setState(newStore)

        }

        handleChange = (e) => {

            const { name, value } = e.target;

            this.setState({

                [name]: value

            }, () => {

                console.log("state", this.state);

            })

        }

        getFieldDecorator = (fieldName, option) => InputCmp => {

            this.options[fieldName] = option;

            return React.cloneElement(InputCmp, {

                name: fieldName,

                value: this.state[fieldName] || "",

                onChange: this.handleChange

            });

        }

        validateFields = (callback) => {

            let err = [];

            for(let fieldName in this.options) {

                if(!this.state[fieldName]) {

                    err.push({

                        [fieldName]: "err"

                    })

                }

            }

            if(err.length === 0) {

                callback(null, {...this.state});

            }else {

                callback(err, {...this.state});

            }

        }

        getForm = () => {

            return {

                getFieldsValue: this.getFieldsValue,

                getFieldValue: this.getFieldValue,

                setFieldsValue: this.setFieldsValue,

                getFieldDecorator: this.getFieldDecorator,

                validateFields: this.validateFields

            }

        }

        render() {

            const form = this.getForm();

            return (

                <div>

                    <Cmp {...this.props} form={form}/>

                </div>

            )

        }

    }

}

打印结果如下:

注意:antd3 的设计有个问题,就是局部变化会引起整体变化,即每次输入框的值发生变化的时候,会重新渲染页面,比较消耗性能,不过 antd4 改进了这个问题。

相关文章

  • React 的几个注意点

    受控组件和无状态组件 非受控组件推荐使用受控组件来实现表单. 在受控组件中, 表单数据是有React组件处理如果让...

  • React - 实现一个Ant Design Form组件(简易

    本篇文章通过对 Ant Design Form 组件的源码分析,实现一个简易版的表单组件,该组件可以实时进行数据校...

  • React-Native 高阶组件

    高阶函数 高阶组件(属性代理)普通组件还可以向高阶组件传值 高阶组件(反向继承) 普通组件的 static 方法怎...

  • react-高阶组件

    高阶组件是代码复用的一种实现方式,用以替代mixin,衍生于高阶函数,即接收一个组件并返回一个组件 基本实现(定义...

  • Vue 子传父 表单控件二次封装

    需求:实现上图表单,封装成组件实现过程:1.子组件:Child 2.父组件使用Child组件 实战: 子组件:Re...

  • React高阶组件HOC

    高阶组件本质是函数,参数是 组件1 返回组件2,高阶组件是为了复用通用逻辑高阶组件eg:import React,...

  • 2021-08-05-🦕🦕 react 高阶组件hotc和@装饰

    简介 高阶组件可以直接调用子组件属性方法;子组件通过 this.props.xxx调用高阶组件方法属性 高阶组件无...

  • 代理以及继承方式的高阶组件

    上一篇文章介绍了简单的高阶组件实现方式,接下来介绍代理和继承方式的高阶组件。 一、代理方式的高阶组件 应用场景:1...

  • 高阶组件实现方式

    参考: 深入理解高阶组件 社区推荐 组合由于继承 高阶组件的主流实现方式: 属性代理 prop proxy 添加p...

  • react与vue中高阶组件的对比

    由高阶函数引申出来的高阶组件 高阶组件本质上也是一个函数,并不是一个组件,且高阶组件是一个纯函数。高阶组件,顾名思...

网友评论

      本文标题:实现高阶组件版表单组件

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