![3be0c9d33f093759e70ade6dcf42e201.png](https://img-blog.csdnimg.cn/img_convert/3be0c9d33f093759e70ade6dcf42e201.png)
前言
首先,让我们来看一看 Ant Design 官网的第一个关于 Modal
的 demo
import { Modal, Button } from 'antd';
class App extends React.Component {
state = { visible: false };
showModal = () => {
this.setState({
visible: true,
});
};
handleOk = e => {
console.log(e);
this.setState({
visible: false,
});
};
handleCancel = e => {
console.log(e);
this.setState({
visible: false,
});
};
render() {
return (
<div>
<Button type="primary" onClick={this.showModal}>
Open Modal
</Button>
<Modal
title="Basic Modal"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</Modal>
</div>
);
}
}
当然,一般来说,我们写的 Modal
不会像官网里的例子这么的简单,毕竟这么简单的话会更倾向于使用类似于 Modal.confirm
等 API 直接调用弹出就好了。我们可能会对 Modal
进行二次封装,里面写一些代码逻辑及可能是固定的譬如 title
直接写在组件内,然后把一些像是 visible
、onOk
及 onCancel
这种 API 用 props
暴露出去。
这种把 visible
提升到父组件的方式固然能解决问题,可是这种方式也导致了一个问题。每次我们打开弹窗的时候,因为 visible
是在父组件中的状态,所以父组件也会重新 render
一次,甚至,如果父组件中的其他子组件没有做优化的话(没有使用 memo