记录一下使用antd的Modal组件遇到的坑
正常使用Modal
import { FC, useState } from "react";
import { SaveOutlined } from '@ant-design/icons';
import { Modal } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import globalStore from '@store/store';
import { runInAction} from "mobx";
const Save: FC<any> = () => {
const { confirm } = Modal;
const showPop = () => {
console.log('showPop');
confirm({
icon: <ExclamationCircleFilled style={{color: "#FF4D4F"}} />,
title: "标题",
content:
<div>
<div>展示内容</div>
<div>
<Select style={{ width: 254 }} placeholder="请选择" onChange={v => {
runInAction(() => {
globalStore.fileType = v;
})
}}
bordered={false}>
<Option value="A">A</Option>
<Option value="B">B</Option>
</Select>s
</div>
<div className={globalStore.fileType ? "hide" : "show"}>
提示:...</div>
</div>,
onOk() {
console.log('OK');
},
onCancel() {
console.log('Cancel');
},
});
}
return (
<div onClick={showPop}>
<SaveOutlined />
</div>
)
}
export default Save;
这种情况会导致confirm的弹框在弹出后没有被更新
原因
confirm的弹框在弹出后没有被更新,网上查了说是闭包原因;
处理方法
import { FC, useEffect, useRef, useState } from "react";
import { Button, Radio, Modal, Select, message } from 'antd';
import { DownloadOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import './ExportData.less';
import { downloadExcel } from '@/utils/excel';
import globalStore from '@store/store';
import { observer, useLocalObservable } from "mobx-react";
import { listTypes } from "@/utils/mock/listType";
import { observable, runInAction, toJS } from "mobx";
const ExportData: FC<any> = () => {
const globalStores = useLocalObservable(() => globalStore);
const { confirm } = Modal;
const { Option } = Select;
let modal: any;
const ModalContent = observer(() => <div className="pop">
<div className="selectbox">
<span className="leftIcon">*</span>
<span className="popcell">文件格式:</span>
<Select style={{ width: 254 }} placeholder="请选择" onChange={v => {
runInAction(() => {
globalStore.fileType = v
})
}}
bordered={false}>
<Option value="xlsx">xlsx</Option>
<Option value="xls">xls</Option>
</Select>
</div>
<div className={globalStore.fileType ? "hide" : "introduce"}>
{globalStore.fileType}请选择导出格式</div>
</div>)
useEffect(() => {
modal && modal.update(prev => ({
...prev,
content: <ModalContent />
}))
}, [globalStore.fileType])
const showPop = () => {
console.log('showPop');
modal = confirm({
icon: <ExclamationCircleFilled style={{ color: "#FF4D4F" }} />,
title: "数据导出",
okText: "导出",
content: <ModalContent />,
onOk() {
if (!globalStore.fileType) {
showPop()
return;
}
onExportExcel()
runInAction(() => {
globalStore.fileType = ''
})
},
onCancel() {
runInAction(() => {
globalStore.fileType = ''
})
},
});
}
return (
<div>
<Button type="primary" icon={<DownloadOutlined />} onClick={() => {
showPop()
}} >
数据导出
</Button>
</div>
)
}
export default observer(ExportData);
|