问题描述
在 React 项目中使用 antd 的 Model(弹窗)组件,官方文档中说:onCancel 是点击遮罩层或右上角叉或取消按钮的回调,言下之意,如果需要在这些动作中关闭 Modal,在这个事件中将控制 Modal 是否可见的 state 置为 false 即可,事实上我也是这么做的
问题出现的环境背景及自己尝试过哪些方法
我有检查过是不是拼写问题,这个可以排除了
另外我也在构造器中将视图层用到的方法 bind(this) 了,context 也没问题
关于方法是否调用?调用了,但在 onCancel 中企图改变 state 的值却失效了,所以导致 Modal 没有关闭,为什么会失效??
相关代码
import { Modal } from 'antd'
class CustomButton extends React.Component {
constructor(props) {
super(props)
this.state = {
popupVisible: true,
wording: '123',
}
this.showCustomPopup = this.showCustomPopup.bind(this)
this.handleCancel = this.handleCancel.bind(this)
}
showCustomPopup() {
this.setState({ popupVisible: true })
}
handleCancel() {
this.setState({
popupVisible: false,
wording: '666'
})
console.log(`visible in state: ${this.state.popupVisible}`)
}
render() {
return (
<div className='container' onClick={this.showCustomPopup}>
<span>
<Modal
visible={this.state.popupVisible}
onCancel={this.handleCancel}
>
{this.state.wording}
</Modal>
</span>
</div>
)
}
}
找到问题了,
对于绑定了事件的 React 组件来说,会依照组件在 React 中的树形结构进行冒泡,比如在最近使用 antd 的过程中,有结构如下:
在点击容器 Modal 弹出之后,点击 Modal 的 取消按钮 / 蒙层 / 关闭图标 都会失效,导致无法关闭 Modal,原因是作为内部元素,Modal 组件的 onClick 事件向上冒泡至容器 div,所以 visible 又变成了 true,需要手动阻止冒泡!