我正在另一个组件中使用ANT Design的模态,例如:
import React from "react";
import {
Modal,
Button
} from "antd";
class SomeModalWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleOk() {
console.log("OK");
}
render() {
const { modalVisible, toggleModal } = this.props;
return (
<Modal
title="Some Title"
visible={modalVisible}
width={300}
className=""
destroyOnClose={true}
footer={[
<Button key="back" onClick={() => toggleModal()}>
Return
</Button>,
<Button key="submit" type="primary" onClick={this.handleOk}>
Submit
</Button>
]}
>
// some other content
</Modal>
);
}
}
export default SomeModalWrapper;
该组件依次由父组件调用,如下所示:
import React from "react";
class SomeComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false
};
}
toggleModal() {
const { modalVisible } = this.state;
this.setState({ modalVisible: !modalVisible });
}
render() {
const { modalVisible } = this.state;
return (
<div>
// some non-modal content
<button onClick={() => this.toggleModal()}>Toggle Modal</button>
<SomeModalWrapper
modalVisible={modalVisible}
toggleModal={this.toggleModal}
/>
</div>
);
}
}
export default SomeComponent;
所有按钮都可以正常工作(显示和隐藏)。但是,当我单击模式外部的区域时,右将自动关闭模式,因为默认情况下maskClosable
属性设置为true
。而且,即使我将其专门设置为maskClosable: true
的形式,它仍然不起作用。
不确定发生了什么吗?是因为模式包装在另一个组件中吗?
答案 0 :(得分:2)
问题不是default value is true
的maskClosable
。
this
绑定到toggleModal
函数。visible={modalVisible}
,这意味着您控制了模态状态,modalVisible
状态将覆盖 maskClosable
。换句话说,maskClosable
不能自行更改状态。class SomeComponent extends React.Component {
state = {
modalVisible: false
};
// bind with named class function or with `.bind()` inside consturctor
toggleModal = () => {
this.setState(prevState => ({ modalVisible: !prevState.modalVisible }));
};
render() {
...
}
}
此外,我建议始终使用onCancel
,如果没有它,您可能会得到意想不到的行为。
<Modal
...
onCancel={toggleModal}
...
>
// some other content
</Modal>;
答案 1 :(得分:1)
您需要在 SomeWrapper 组件中传递onCancel道具:即 Somewrapper.js
<Modal
title="Some Title"
visible={modalVisible}
width={300}
className=""
onCancel={toggleModal} //pass close logic here
destroyOnClose={true}
footer={[
<Button key="back" onClick={() => toggleModal()}>
Return
</Button>,
<Button key="submit" type="primary" onClick={this.handleOk}>
Submit
</Button>
]}
>
// some other content
</Modal>
答案 2 :(得分:1)
为犯过我错误的人添加此内容:
我阅读了有关“ onOk”功能的文档:
“指定当用户单击“确定”按钮时将调用的函数”
尽管实际上列出了以下内容,但下意识地填充了“ onCancel”的功能与onOk的相反:
'指定当用户单击蒙版,右上角的关闭按钮或“取消”按钮'时要调用的函数。
不仅因为我自己的粗心,而且还因为他们的Api命名不一致。
onCancel应该与它们的API其他组件(例如“抽屉”)中的命名更一致,在更恰当地命名的属性“ onClose”中可以找到相同的功能,以减少混乱