han's bolg - 年糕記

antd-modal源码解析

antd modal弹窗模块,是基于rc-dialog进行二次开发的。代码部分在src/components/modal中就是modal部分的源码。

将antd modal源码扒下来,ts改为js,代码在这里:https://github.com/handv/antd-modal

rc-dialog参数




























































name type default description
getContainer HTMLElement | () => HTMLElement | Selectors | false document.body 指定 Modal 挂载的 HTML 节点, false 为挂载在当前 dom
prefixCls string rc-dialog dialog节点的类名前缀
wrapClassName string 对话框外层容器的类名
footer string|ReactNode 确定取消按钮 底部内容,当不需要默认底部按钮时,可以设为 footer={null}
visible boolean false 对话框是否可见
mousePosition {x:number,y:number} 设置当前鼠标的坐标pageX和pageY
onClose function 点击关闭图标或蒙层时调用
closeIcon ReactNode 自定义关闭图标

原理

  • footer

modal有一个默认footer,带确定取消的两个ActionButton

  • ActionButton

二次封装后的antd-Button,带一个onClick方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
onClick = () => {
const { actionFn, closeModal } = this.props;
if (actionFn) {
let ret;
if (actionFn.length) {
ret = actionFn(closeModal);
} else {
ret = actionFn();
if (!ret) {
closeModal();
}
}
if (ret && ret.then) {
this.setState({ loading: true });
ret.then(
(...args) => {
// It's unnecessary to set loading=false, for the Modal will be unmounted after close.
// this.setState({ loading: false });
closeModal(...args);
},
(e) => {
// Emit error when catch promise reject
// eslint-disable-next-line no-console
console.error(e);
// See: https://github.com/ant-design/ant-design/issues/6183
this.setState({ loading: false });
},
);
}
} else {
closeModal();
}
};
  • Modal.info / Modal.error / Modal.warn / Modal.success

代码见src/components/modal/index.js, footer={null}

此部分实现了一个confirm(…props)方法。

  • confirm里有个visible的参数,还有一个render的方法。在执行confirm()的时候,会调用render()生成一个
  • confirm里还有一个close方法,在点击右上角关闭的时候,会调用close(),生成一个