美文网首页
Antd Modal的封装

Antd Modal的封装

作者: TimeMage | 来源:发表于2019-04-18 16:44 被阅读0次

    Antd Modal 在实际前端项目中很常用。在实际使用中,要在包含Modal的父组件类里设置state控制Modal的显示,handleOK,onClick回调函数绑定在anchor和modal上,可以改变state的状态。这对所有对话框是通用的,因此可以封装起来,减少代码的编写量。

    前置知识

    react的基础知识,antd库的使用

    代码

    ModalFactory

    const ModalFactory = {
        LoginModal() {
            return <BaseModal hint='登录'
                        title='请登录'
                        form={LoginForm}
                    />
        },
        ProfileModal() {
            return <BaseModal hint='编辑'
                        title='修改用户信息'
                        form={ProfileForm}
                    />
        },
        AccountModal({hint='编辑', type, account={}}) {
            return <BaseModal hint={hint}
                        title='账号修改'
                        form={
                            props=>(
                                <AccountForm {...props}
                                    account={account}
                                />
                            )
                        }
                        type={type}
                    />
        }
    }
    

    BaseModal

    
    class BaseModal extends React.Component {
        state = {
            visible: false,
        }
        showModal = (e)=>{
            console.log(`show ${this.props.hint} modal`)
            e.preventDefault()
            this.setState({visible:true})
        }
        handleCancel = ()=>{
            console.log(`hide ${this.props.hint} modal`)
            this.setState({visible:false})
        }
        handleOK = ()=>{
            console.log(`hide ${this.props.hint} modal`)
            this.setState({visible:false})
        }
        renderAnchor = ()=>{
            if(this.props.type=='button') {
                return <Button type='primary' onClick={this.showModal}>{this.props.hint}</Button>
            } 
            return <span style={{ color :'blue'}} onClick={this.showModal}>{this.props.hint}</span>
        }
        render() {
            console.log(`show ${this.props.hint} span`)
            const Component = this.props.form
    
            return (
                <span>
                    {this.renderAnchor()}
                    <Modal title={this.props.title} visible={this.state.visible}
                        footer={null}
                        onOk={this.handleOK}
                        onCancel={this.handleCancel}>
                        <Component onSubmit={this.handleOK}/>
                    </Modal>
                </span>
            )
        }
    }
    

    使用

    const LoginModal = ModalFactory.LoginModal
    const View = ()=><LoginModal/>
    

    相关文章

      网友评论

          本文标题:Antd Modal的封装

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