• Modal对话框
    • 何时使用
    • 代码演示
    • API
      • 注意
    • Modal.method()

    Modal对话框

    模态对话框。

    何时使用

    需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 Modal 在当前页面正中打开一个浮层,承载相应的操作。

    另外当需要一个简洁的确认框询问用户时,可以使用 Modal.confirm() 等语法糖方法。

    代码演示

    Modal 对话框 - 图1

    基本

    第一个对话框。

    1. import { Modal, Button } from 'antd';
    2. class App extends React.Component {
    3. state = { visible: false };
    4. showModal = () => {
    5. this.setState({
    6. visible: true,
    7. });
    8. };
    9. handleOk = e => {
    10. console.log(e);
    11. this.setState({
    12. visible: false,
    13. });
    14. };
    15. handleCancel = e => {
    16. console.log(e);
    17. this.setState({
    18. visible: false,
    19. });
    20. };
    21. render() {
    22. return (
    23. <div>
    24. <Button type="primary" onClick={this.showModal}>
    25. Open Modal
    26. </Button>
    27. <Modal
    28. title="Basic Modal"
    29. visible={this.state.visible}
    30. onOk={this.handleOk}
    31. onCancel={this.handleCancel}
    32. >
    33. <p>Some contents...</p>
    34. <p>Some contents...</p>
    35. <p>Some contents...</p>
    36. </Modal>
    37. </div>
    38. );
    39. }
    40. }
    41. ReactDOM.render(<App />, mountNode);

    Modal 对话框 - 图2

    自定义页脚

    更复杂的例子,自定义了页脚的按钮,点击提交后进入 loading 状态,完成后关闭。

    不需要默认确定取消按钮时,你可以把 footer 设为 null

    1. import { Modal, Button } from 'antd';
    2. class App extends React.Component {
    3. state = {
    4. loading: false,
    5. visible: false,
    6. };
    7. showModal = () => {
    8. this.setState({
    9. visible: true,
    10. });
    11. };
    12. handleOk = () => {
    13. this.setState({ loading: true });
    14. setTimeout(() => {
    15. this.setState({ loading: false, visible: false });
    16. }, 3000);
    17. };
    18. handleCancel = () => {
    19. this.setState({ visible: false });
    20. };
    21. render() {
    22. const { visible, loading } = this.state;
    23. return (
    24. <div>
    25. <Button type="primary" onClick={this.showModal}>
    26. Open Modal with customized footer
    27. </Button>
    28. <Modal
    29. visible={visible}
    30. title="Title"
    31. onOk={this.handleOk}
    32. onCancel={this.handleCancel}
    33. footer={[
    34. <Button key="back" onClick={this.handleCancel}>
    35. Return
    36. </Button>,
    37. <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
    38. Submit
    39. </Button>,
    40. ]}
    41. >
    42. <p>Some contents...</p>
    43. <p>Some contents...</p>
    44. <p>Some contents...</p>
    45. <p>Some contents...</p>
    46. <p>Some contents...</p>
    47. </Modal>
    48. </div>
    49. );
    50. }
    51. }
    52. ReactDOM.render(<App />, mountNode);

    Modal 对话框 - 图3

    确认对话框

    使用 confirm() 可以快捷地弹出确认框。onCancel/onOk 返回 promise 可以延迟关闭。

    1. import { Modal, Button } from 'antd';
    2. const confirm = Modal.confirm;
    3. function showConfirm() {
    4. confirm({
    5. title: 'Do you want to delete these items?',
    6. content: 'When clicked the OK button, this dialog will be closed after 1 second',
    7. onOk() {
    8. return new Promise((resolve, reject) => {
    9. setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
    10. }).catch(() => console.log('Oops errors!'));
    11. },
    12. onCancel() {},
    13. });
    14. }
    15. ReactDOM.render(<Button onClick={showConfirm}>Confirm</Button>, mountNode);

    Modal 对话框 - 图4

    国际化

    设置 okTextcancelText 以自定义按钮文字。

    1. import { Modal, Button } from 'antd';
    2. class LocalizedModal extends React.Component {
    3. state = { visible: false };
    4. showModal = () => {
    5. this.setState({
    6. visible: true,
    7. });
    8. };
    9. hideModal = () => {
    10. this.setState({
    11. visible: false,
    12. });
    13. };
    14. render() {
    15. return (
    16. <div>
    17. <Button type="primary" onClick={this.showModal}>
    18. Modal
    19. </Button>
    20. <Modal
    21. title="Modal"
    22. visible={this.state.visible}
    23. onOk={this.hideModal}
    24. onCancel={this.hideModal}
    25. okText="确认"
    26. cancelText="取消"
    27. >
    28. <p>Bla bla ...</p>
    29. <p>Bla bla ...</p>
    30. <p>Bla bla ...</p>
    31. </Modal>
    32. </div>
    33. );
    34. }
    35. }
    36. function confirm() {
    37. Modal.confirm({
    38. title: 'Confirm',
    39. content: 'Bla bla ...',
    40. okText: '确认',
    41. cancelText: '取消',
    42. });
    43. }
    44. ReactDOM.render(
    45. <div>
    46. <LocalizedModal />
    47. <br />
    48. <Button onClick={confirm}>Confirm</Button>
    49. </div>,
    50. mountNode,
    51. );

    Modal 对话框 - 图5

    自定义位置

    使用 centered 或类似 style.top 的样式来设置对话框位置。

    1. import { Modal, Button } from 'antd';
    2. class App extends React.Component {
    3. state = {
    4. modal1Visible: false,
    5. modal2Visible: false,
    6. };
    7. setModal1Visible(modal1Visible) {
    8. this.setState({ modal1Visible });
    9. }
    10. setModal2Visible(modal2Visible) {
    11. this.setState({ modal2Visible });
    12. }
    13. render() {
    14. return (
    15. <div>
    16. <Button type="primary" onClick={() => this.setModal1Visible(true)}>
    17. Display a modal dialog at 20px to Top
    18. </Button>
    19. <Modal
    20. title="20px to Top"
    21. style={{ top: 20 }}
    22. visible={this.state.modal1Visible}
    23. onOk={() => this.setModal1Visible(false)}
    24. onCancel={() => this.setModal1Visible(false)}
    25. >
    26. <p>some contents...</p>
    27. <p>some contents...</p>
    28. <p>some contents...</p>
    29. </Modal>
    30. <br />
    31. <br />
    32. <Button type="primary" onClick={() => this.setModal2Visible(true)}>
    33. Vertically centered modal dialog
    34. </Button>
    35. <Modal
    36. title="Vertically centered modal dialog"
    37. centered
    38. visible={this.state.modal2Visible}
    39. onOk={() => this.setModal2Visible(false)}
    40. onCancel={() => this.setModal2Visible(false)}
    41. >
    42. <p>some contents...</p>
    43. <p>some contents...</p>
    44. <p>some contents...</p>
    45. </Modal>
    46. </div>
    47. );
    48. }
    49. }
    50. ReactDOM.render(<App />, mountNode);

    Modal 对话框 - 图6

    自定义页脚按钮属性

    传入 okButtonPropscancelButtonProps 可分别自定义确定按钮和取消按钮的 props。

    1. import { Modal, Button } from 'antd';
    2. class App extends React.Component {
    3. state = { visible: false };
    4. showModal = () => {
    5. this.setState({
    6. visible: true,
    7. });
    8. };
    9. handleOk = e => {
    10. console.log(e);
    11. this.setState({
    12. visible: false,
    13. });
    14. };
    15. handleCancel = e => {
    16. console.log(e);
    17. this.setState({
    18. visible: false,
    19. });
    20. };
    21. render() {
    22. return (
    23. <div>
    24. <Button type="primary" onClick={this.showModal}>
    25. Open Modal with customized button props
    26. </Button>
    27. <Modal
    28. title="Basic Modal"
    29. visible={this.state.visible}
    30. onOk={this.handleOk}
    31. onCancel={this.handleCancel}
    32. okButtonProps={{ disabled: true }}
    33. cancelButtonProps={{ disabled: true }}
    34. >
    35. <p>Some contents...</p>
    36. <p>Some contents...</p>
    37. <p>Some contents...</p>
    38. </Modal>
    39. </div>
    40. );
    41. }
    42. }
    43. ReactDOM.render(<App />, mountNode);

    Modal 对话框 - 图7

    异步关闭

    点击确定后异步关闭对话框,例如提交表单。

    1. import { Modal, Button } from 'antd';
    2. class App extends React.Component {
    3. state = {
    4. ModalText: 'Content of the modal',
    5. visible: false,
    6. confirmLoading: false,
    7. };
    8. showModal = () => {
    9. this.setState({
    10. visible: true,
    11. });
    12. };
    13. handleOk = () => {
    14. this.setState({
    15. ModalText: 'The modal will be closed after two seconds',
    16. confirmLoading: true,
    17. });
    18. setTimeout(() => {
    19. this.setState({
    20. visible: false,
    21. confirmLoading: false,
    22. });
    23. }, 2000);
    24. };
    25. handleCancel = () => {
    26. console.log('Clicked cancel button');
    27. this.setState({
    28. visible: false,
    29. });
    30. };
    31. render() {
    32. const { visible, confirmLoading, ModalText } = this.state;
    33. return (
    34. <div>
    35. <Button type="primary" onClick={this.showModal}>
    36. Open Modal with async logic
    37. </Button>
    38. <Modal
    39. title="Title"
    40. visible={visible}
    41. onOk={this.handleOk}
    42. confirmLoading={confirmLoading}
    43. onCancel={this.handleCancel}
    44. >
    45. <p>{ModalText}</p>
    46. </Modal>
    47. </div>
    48. );
    49. }
    50. }
    51. ReactDOM.render(<App />, mountNode);

    Modal 对话框 - 图8

    确认对话框

    使用 confirm() 可以快捷地弹出确认框。

    1. import { Modal, Button } from 'antd';
    2. const confirm = Modal.confirm;
    3. function showConfirm() {
    4. confirm({
    5. title: 'Do you Want to delete these items?',
    6. content: 'Some descriptions',
    7. onOk() {
    8. console.log('OK');
    9. },
    10. onCancel() {
    11. console.log('Cancel');
    12. },
    13. });
    14. }
    15. function showDeleteConfirm() {
    16. confirm({
    17. title: 'Are you sure delete this task?',
    18. content: 'Some descriptions',
    19. okText: 'Yes',
    20. okType: 'danger',
    21. cancelText: 'No',
    22. onOk() {
    23. console.log('OK');
    24. },
    25. onCancel() {
    26. console.log('Cancel');
    27. },
    28. });
    29. }
    30. function showPropsConfirm() {
    31. confirm({
    32. title: 'Are you sure delete this task?',
    33. content: 'Some descriptions',
    34. okText: 'Yes',
    35. okType: 'danger',
    36. okButtonProps: {
    37. disabled: true,
    38. },
    39. cancelText: 'No',
    40. onOk() {
    41. console.log('OK');
    42. },
    43. onCancel() {
    44. console.log('Cancel');
    45. },
    46. });
    47. }
    48. ReactDOM.render(
    49. <div>
    50. <Button onClick={showConfirm}>Confirm</Button>
    51. <Button onClick={showDeleteConfirm} type="dashed">
    52. Delete
    53. </Button>
    54. <Button onClick={showPropsConfirm} type="dashed">
    55. With extra props
    56. </Button>
    57. </div>,
    58. mountNode,
    59. );

    Modal 对话框 - 图9

    信息提示

    各种类型的信息提示,只提供一个按钮用于关闭。

    1. import { Modal, Button } from 'antd';
    2. function info() {
    3. Modal.info({
    4. title: 'This is a notification message',
    5. content: (
    6. <div>
    7. <p>some messages...some messages...</p>
    8. <p>some messages...some messages...</p>
    9. </div>
    10. ),
    11. onOk() {},
    12. });
    13. }
    14. function success() {
    15. Modal.success({
    16. title: 'This is a success message',
    17. content: 'some messages...some messages...',
    18. });
    19. }
    20. function error() {
    21. Modal.error({
    22. title: 'This is an error message',
    23. content: 'some messages...some messages...',
    24. });
    25. }
    26. function warning() {
    27. Modal.warning({
    28. title: 'This is a warning message',
    29. content: 'some messages...some messages...',
    30. });
    31. }
    32. ReactDOM.render(
    33. <div>
    34. <Button onClick={info}>Info</Button>
    35. <Button onClick={success}>Success</Button>
    36. <Button onClick={error}>Error</Button>
    37. <Button onClick={warning}>Warning</Button>
    38. </div>,
    39. mountNode,
    40. );

    Modal 对话框 - 图10

    手动更新和移除

    手动更新和关闭 Modal.method 方式创建的对话框。

    1. import { Modal, Button } from 'antd';
    2. function countDown() {
    3. let secondsToGo = 5;
    4. const modal = Modal.success({
    5. title: 'This is a notification message',
    6. content: `This modal will be destroyed after ${secondsToGo} second.`,
    7. });
    8. const timer = setInterval(() => {
    9. secondsToGo -= 1;
    10. modal.update({
    11. content: `This modal will be destroyed after ${secondsToGo} second.`,
    12. });
    13. }, 1000);
    14. setTimeout(() => {
    15. clearInterval(timer);
    16. modal.destroy();
    17. }, secondsToGo * 1000);
    18. }
    19. ReactDOM.render(<Button onClick={countDown}>Open modal to close in 5s</Button>, mountNode);

    Modal 对话框 - 图11

    销毁确认对话框

    使用 Modal.destroyAll() 可以销毁弹出的确认窗。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题。

    1. import { Modal, Button } from 'antd';
    2. function destroyAll() {
    3. Modal.destroyAll();
    4. }
    5. const confirm = Modal.confirm;
    6. function showConfirm() {
    7. for (let i = 0; i < 3; i += 1) {
    8. setTimeout(() => {
    9. confirm({
    10. content: <Button onClick={destroyAll}>Click to destroy all</Button>,
    11. onOk() {
    12. console.log('OK');
    13. },
    14. onCancel() {
    15. console.log('Cancel');
    16. },
    17. });
    18. }, i * 500);
    19. }
    20. }
    21. ReactDOM.render(
    22. <div>
    23. <Button onClick={showConfirm}>Confirm</Button>
    24. </div>,
    25. mountNode,
    26. );

    API

    参数说明类型默认值
    afterCloseModal 完全关闭后的回调function
    bodyStyleModal body 样式object{}
    cancelText取消按钮文字string|ReactNode取消
    centered垂直居中展示 ModalBooleanfalse
    closable是否显示右上角的关闭按钮booleantrue
    confirmLoading确定按钮 loadingboolean
    destroyOnClose关闭时销毁 Modal 里的子元素booleanfalse
    footer底部内容,当不需要默认底部按钮时,可以设为 footer={null}string|ReactNode确定取消按钮
    forceRender强制渲染 Modalbooleanfalse
    getContainer指定 Modal 挂载的 HTML 节点(instance): HTMLElement() => document.body
    keyboard是否支持键盘 esc 关闭booleantrue
    mask是否展示遮罩Booleantrue
    maskClosable点击蒙层是否允许关闭booleantrue
    maskStyle遮罩样式object{}
    okText确认按钮文字string|ReactNode确定
    okType确认按钮类型stringprimary
    okButtonPropsok 按钮 propsButtonProps-
    cancelButtonPropscancel 按钮 propsButtonProps-
    style可用于设置浮层的样式,调整浮层位置等object-
    title标题string|ReactNode
    visible对话框是否可见boolean
    width宽度string|number520
    wrapClassName对话框外层容器的类名string-
    zIndex设置 Modal 的 z-indexNumber1000
    onCancel点击遮罩层或右上角叉或取消按钮的回调function(e)
    onOk点击确定回调function(e)

    注意

    <Modal /> 默认关闭后状态不会自动清空, 如果希望每次打开都是新内容,请设置 destroyOnClose

    Modal.method()

    包括:

    • Modal.info

    • Modal.success

    • Modal.error

    • Modal.warning

    • Modal.confirm

    以上均为一个函数,参数为 object,具体属性如下:

    参数说明类型默认值
    autoFocusButton指定自动获得焦点的按钮null|string: ok cancelok
    cancelText取消按钮文字string取消
    centered垂直居中展示 ModalBooleanfalse
    className容器类名string-
    content内容string|ReactNode
    icon自定义图标(3.12.0 新增)string|ReactNode<Icon type="question-circle">
    iconType图标类型(3.12.0 后废弃,请使用 iconstringquestion-circle
    mask是否展示遮罩Booleantrue
    maskClosable点击蒙层是否允许关闭Booleanfalse
    okText确认按钮文字string确定
    okType确认按钮类型stringprimary
    okButtonPropsok 按钮 propsButtonProps-
    cancelButtonPropscancel 按钮 propsButtonProps-
    title标题string|ReactNode
    width宽度string|number416
    zIndex设置 Modal 的 z-indexNumber1000
    onCancel取消回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function
    onOk点击确定回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function

    以上函数调用后,会返回一个引用,可以通过该引用更新和关闭弹窗。

    1. const modal = Modal.info();
    2. modal.update({
    3. title: '修改的标题',
    4. content: '修改的内容',
    5. });
    6. modal.destroy();
    • Modal.destroyAll

    使用 Modal.destroyAll() 可以销毁弹出的确认窗(即上述的 Modal.info、Modal.success、Modal.error、Modal.warning、Modal.confirm)。通常用于路由监听当中,处理路由前进、后退不能销毁确认对话框的问题,而不用各处去使用实例的返回值进行关闭(modal.destroy() 适用于主动关闭,而不是路由这样被动关闭)

    1. import { browserHistory } from 'react-router';
    2. // router change
    3. browserHistory.listen(() => {
    4. Modal.destroyAll();
    5. });