美文网首页让前端飞react实战
react封装一个可自定义内容的modal弹框组件

react封装一个可自定义内容的modal弹框组件

作者: 全栈弄潮儿 | 来源:发表于2018-12-29 10:57 被阅读4次

使用方法:

npm i react-component-modal -S

import CustomModal from 'react-component-modal';

constructor(props) {
    super(props);
    this.handleClose = this.handleClose.bind(this);
    this.closeModal = this.closeModal.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
        visible: false
    };
}

render(){
  const { visible } = this.state;
  return (
    <CustomModal visible={visible} title="标题" negative_button_text="取消" positive_button_text="确定" hideModal={this.closeModal} handleSubmit={this.handleSubmit}>
        <div>
            <p>自定义内容</p>
        </div>
    </CustomModal>
  )
}

showModal() {
    this.setState({visible: true});
}
closeModal() {
    this.setState({visible: false});
}
handleSubmit() {
    this.setState({visible: false});
    //
}

组件地址github

部分源码:

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import { Modal } from 'antd-mobile';

class CustomModal extends Component {
    constructor(props) {
        super(props);
        this.hideModal = this.hideModal.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    render() {
        const { visible, title, negative_button_text, positive_button_text, children } = this.props;
        return (
            <Modal
                visible={visible}
                transparent
                maskClosable={false}
                title={title}
                onClose={this.hideModal}
                footer={[
                    { text: negative_button_text, onPress: this.hideModal},
                    { text: positive_button_text, onPress: this.handleSubmit} 
                ]}
                wrapProps={{ onTouchStart: this.onWrapTouchStart }}
            >
                {children}
            </Modal>
        );
    }

    hideModal() {//hide modal
        const {hideModal} = this.props;
        hideModal();
    }

    handleSubmit() {//submit
        const {handleSubmit} = this.props;
        handleSubmit();
    }
}

CustomModal.propTypes = {//参数类型及是否必传
    visible: PropTypes.bool,
    title: PropTypes.string,
    negative_button_text: PropTypes.string.isRequired,
    positive_button_text: PropTypes.string.isRequired,
    children: PropTypes.node //自定义内容
};

CustomModal.defaultProps = {//默认参数
    visible: false,
    title: '标题',
    negative_button_text: '取消',
    positive_button_text: '确定'
};

export default CustomModal;

组件地址github

更多angular1/2/4/5、ionic1/2/3、react、vue、微信小程序、nodejs等技术文章、视频教程和开源项目,请关注微信公众号——全栈弄潮儿

微信公众号.png

前端最火框架排行榜——小程序二维码

前端排行榜.png

相关文章

网友评论

    本文标题:react封装一个可自定义内容的modal弹框组件

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