Modal对话框

模态对话框。

何时使用#

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

另外当需要一个简洁的确认框询问用户时,可以使用精心封装好的 antd.Modal.confirm() 等方法。

代码演示

第一个对话框。

expand codeexpand code
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</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>
    );
  }
}

ReactDOM.render(<App />, mountNode);

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

expand codeexpand code
import { Modal, Button } from 'antd';
const confirm = Modal.confirm;

function showConfirm() {
  confirm({
    title: 'Do you want to delete these items?',
    content: 'When clicked the OK button, this dialog will be closed after 1 second',
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
      }).catch(() => console.log('Oops errors!'));
    },
    onCancel() {},
  });
}

ReactDOM.render(
  <Button onClick={showConfirm}>
    Confirm
  </Button>
, mountNode);

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

expand codeexpand code
import { Modal, Button } from 'antd';

class LocalizedModal extends React.Component {
  state = { visible: false }
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  hideModal = () => {
    this.setState({
      visible: false,
    });
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>Modal</Button>
        <Modal
          title="Modal"
          visible={this.state.visible}
          onOk={this.hideModal}
          onCancel={this.hideModal}
          okText="确认"
          cancelText="取消"
        >
          <p>Bla bla ...</p>
          <p>Bla bla ...</p>
          <p>Bla bla ...</p>
        </Modal>
      </div>
    );
  }
}

function confirm() {
  Modal.confirm({
    title: 'Confirm',
    content: 'Bla bla ...',
    okText: '确认',
    cancelText: '取消',
  });
}

ReactDOM.render(
  <div>
    <LocalizedModal />
    <br />
    <Button onClick={confirm}>Confirm</Button>
  </div>,
  mountNode
);


1.0 之后,Modal 的 align 属性被移除,您可以直接使用 style.top 或配合其他样式来设置对话框位置。

expand codeexpand code
import { Modal, Button } from 'antd';

class App extends React.Component {
  state = {
    modal1Visible: false,
    modal2Visible: false,
  }
  setModal1Visible(modal1Visible) {
    this.setState({ modal1Visible });
  }
  setModal2Visible(modal2Visible) {
    this.setState({ modal2Visible });
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={() => this.setModal1Visible(true)}>Display a modal dialog at 20px to Top</Button>
        <Modal
          title="20px to Top"
          style={{ top: 20 }}
          visible={this.state.modal1Visible}
          onOk={() => this.setModal1Visible(false)}
          onCancel={() => this.setModal1Visible(false)}
        >
          <p>some contents...</p>
          <p>some contents...</p>
          <p>some contents...</p>
        </Modal>
        <br /><br />
        <Button type="primary" onClick={() => this.setModal2Visible(true)}>Vertically centered modal dialog</Button>
        <Modal
          title="Vertically centered modal dialog"
          wrapClassName="vertical-center-modal"
          visible={this.state.modal2Visible}
          onOk={() => this.setModal2Visible(false)}
          onCancel={() => this.setModal2Visible(false)}
        >
          <p>some contents...</p>
          <p>some contents...</p>
          <p>some contents...</p>
        </Modal>
      </div>
    );
  }
}

ReactDOM.render(<App />, mountNode);
/* use css to set position of modal */
.vertical-center-modal {
  text-align: center;
  white-space: nowrap;
}

.vertical-center-modal:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width: 0;
}

.vertical-center-modal .ant-modal {
  display: inline-block;
  vertical-align: middle;
  top: 0;
  text-align: left;
}

/*
// Use flex which not working in IE
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;
}

.vertical-center-modal .ant-modal {
  top: 0;
}
*/

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

expand codeexpand code
import { Modal, Button } from 'antd';

class App extends React.Component {
  state = {
    ModalText: 'Content of the modal',
    visible: false,
    confirmLoading: false,
  }
  showModal = () => {
    this.setState({
      visible: true,
    });
  }
  handleOk = () => {
    this.setState({
      ModalText: 'The modal will be closed after two seconds',
      confirmLoading: true,
    });
    setTimeout(() => {
      this.setState({
        visible: false,
        confirmLoading: false,
      });
    }, 2000);
  }
  handleCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      visible: false,
    });
  }
  render() {
    const { visible, confirmLoading, ModalText } = this.state;
    return (
      <div>
        <Button type="primary" onClick={this.showModal}>Open</Button>
        <Modal title="Title"
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={confirmLoading}
          onCancel={this.handleCancel}
        >
          <p>{ModalText}</p>
        </Modal>
      </div>
    );
  }
}

ReactDOM.render(<App />, mountNode);

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

expand codeexpand code
import { Modal, Button } from 'antd';
const confirm = Modal.confirm;

function showConfirm() {
  confirm({
    title: 'Do you Want to delete these items?',
    content: 'Some descriptions',
    onOk() {
      console.log('OK');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

function showDeleteConfirm() {
  confirm({
    title: 'Are you sure delete this task?',
    content: 'Some descriptions',
    okText: 'Yes',
    okType: 'danger',
    cancelText: 'No',
    onOk() {
      console.log('OK');
    },
    onCancel() {
      console.log('Cancel');
    },
  });
}

ReactDOM.render(
  <div>
    <Button onClick={showConfirm}>
      Confirm
    </Button>
    <Button onClick={showDeleteConfirm} type="dashed">
      Delete
    </Button>
  </div>
, mountNode);

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

expand codeexpand code
import { Modal, Button } from 'antd';

function info() {
  Modal.info({
    title: 'This is a notification message',
    content: (
      <div>
        <p>some messages...some messages...</p>
        <p>some messages...some messages...</p>
      </div>
    ),
    onOk() {},
  });
}

function success() {
  Modal.success({
    title: 'This is a success message',
    content: 'some messages...some messages...',
  });
}

function error() {
  Modal.error({
    title: 'This is an error message',
    content: 'some messages...some messages...',
  });
}

function warning() {
  Modal.warning({
    title: 'This is a warning message',
    content: 'some messages...some messages...',
  });
}

ReactDOM.render(
  <div>
    <Button onClick={info}>Info</Button>
    <Button onClick={success}>Success</Button>
    <Button onClick={error}>Error</Button>
    <Button onClick={warning}>Warning</Button>
  </div>,
  mountNode
);

手动关闭modal。

expand codeexpand code
import { Modal, Button } from 'antd';

function success() {
  const modal = Modal.success({
    title: 'This is a notification message',
    content: 'This modal will be destroyed after 1 second',
  });
  setTimeout(() => modal.destroy(), 1000);
}


ReactDOM.render(
  <Button onClick={success}>Success</Button>,
  mountNode
);

API#

参数说明类型默认值
visible对话框是否可见boolean
confirmLoading确定按钮 loadingboolean
title标题string|ReactNode
closable是否显示右上角的关闭按钮booleantrue
onOk点击确定回调function(e)
onCancel点击遮罩层或右上角叉或取消按钮的回调function(e)
width宽度string|number520
footer底部内容,当不需要默认底部按钮时,可以设为 footer={null}string|ReactNode确定取消按钮
okText确认按钮文字string确定
okType确认按钮类型stringprimary
cancelText取消按钮文字string取消
maskClosable点击蒙层是否允许关闭booleantrue
style可用于设置浮层的样式,调整浮层位置等object-
wrapClassName对话框外层容器的类名string-
afterCloseModal 完全关闭后的回调function
getContainer指定 Modal 挂载的 HTML 节点(instance): HTMLElement() => document.body
zIndex设置 Modal 的 z-indexNumber1000

清空旧数据#

<Modal /> 组件有标准的 React 生命周期,关闭后状态不会自动清空。 如果希望每次打开都是新内容,需要自行手动清空旧的状态。

Modal.method()#

包括:

  • Modal.info

  • Modal.success

  • Modal.error

  • Modal.warning

  • Modal.confirm

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

参数说明类型默认值
title标题string|ReactNode
content内容string|ReactNode
onOk点击确定回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function
onCancel取消回调,参数为关闭函数,返回 promise 时 resolve 后自动关闭function
width宽度string|number416
iconType图标 Icon 类型stringquestion-circle
okText确认按钮文字string确定
okType确认按钮类型stringprimary
cancelText取消按钮文字string取消
maskClosable点击蒙层是否允许关闭Booleanfalse
zIndex设置 Modal 的 z-indexNumber1000

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

const ref = Modal.info();
ref.destroy();