在项目中使用到了 antd 的 Modal.confirm 方法, 发现获取不到 this
项目中需求是这样的: 点击删除的时候, 弹出 confirm 框, 点击 OK 的时候请求删除接口
D500192C-1CD4-416B-9BD2-A37945D41E42.PNG
项目中的代码如下:
- const confirm = Modal.confirm;
- confirm({
- title: '确定要删除吗?',
- onOk(){
- this.requestDelete()
- })
- },
- onCancel() {
- console.log('Cancel');
- },
- });
但是, 这样的话会报错: 打印出来的 this 是 undefined, 后来查了一下需要对方法做一下修改才能获取到 this. 修改如下: 将 onOk() 改为箭头函数形式: onOk: ()=>{}
- const confirm = Modal.confirm;
- confirm({
- title: '确定要删除吗?',
- onOk :()=>{
- this.requestDelete()
- })
- },
- onCancel() {
- console.log('Cancel');
- },
- });
来源: http://www.jianshu.com/p/2f312c8b2e21