Antd Modal的封装

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/>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,526评论 1 33
  • 说好了React苦海无涯回头是岸结果工作需要还是得往坑里跳听了两天培训什么也没有听懂前端代码里写逻辑的都去枪毙 R...
    saint37阅读 7,219评论 3 14
  • HTML模版 之后出现的React代码嵌套入模版中。 1. Hello world 这段代码将一个一级标题插入到指...
    ryanho84阅读 6,308评论 0 9
  • 前端开发面试题 <a name='preface'>前言</a> 只看问题点这里 看全部问题和答案点这里 本文由我...
    自you是敏感词阅读 786评论 0 3
  • 最近看了一本关于学习方法论的书,强调了记笔记和坚持的重要性。这几天也刚好在学习React,所以我打算每天坚持一篇R...
    gaoer1938阅读 1,730评论 0 5