antd#Modal TypeScript Examples
The following examples show how to use
antd#Modal.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: download.ts From generator-earth with MIT License | 6 votes |
downloadByIframe = (url: string, time = 1) => {
if (!url) {
message.warn('下载失败,下载地址为空!')
return
}
const iframe = document.createElement('iframe')
iframe.style.display = 'none' // 防止影响页面
iframe.style.height = '0' // 防止影响页面
iframe.src = url
document.body.appendChild(iframe) // 这一行必须,iframe挂在到dom树上才会发请求
// 3分钟之后删除(onload方法对于下载链接不起作用,就先抠脚一下吧)
setTimeout(() => {
iframe && iframe.remove()
}, 3 * 60 * 1000)
setTimeout(() => {
if (!iframe) return
const el = iframe.contentWindow || iframe.contentDocument
if (!el) return
try {
// eslint-disable-next-line
el.location.href
} catch (err) {
// err:SecurityError: Blocked a frame with origin 'http://*********' from accessing a cross-origin frame.
console.log(err)
Modal.error({
title: '下载失败',
content: `下载地址:${url}`
})
iframe && iframe.remove()
}
}, time * 1000)
}
Example #2
Source File: ImagePreview.tsx From jmix-frontend with Apache License 2.0 | 6 votes |
render() {
const {intl, isVisible, isLoading, objectUrl, fileName, onClose} = this.props;
return (
<Modal title={intl.formatMessage({id: 'jmix.imagePreview.title'})}
visible={isVisible}
afterClose={onClose}
onCancel={onClose}
onOk={this.saveFile}
cancelText={intl.formatMessage({id: 'jmix.imagePreview.close'})}
okText={intl.formatMessage({id: 'jmix.imagePreview.download'})}
okButtonProps={this.okButtonProps}
destroyOnClose={true}
width='80vw'
>
{isLoading && (
<div className={styles.spinner}>
<Spinner/>
</div>
)}
{!isLoading && objectUrl != null && fileName != null && (
<div className={styles.imagePreview}>
<div className={styles.title}>
{fileName}
</div>
<img src={objectUrl}
alt={intl.formatMessage({id: 'jmix.imagePreview.alt'})}
className={styles.image}
/>
</div>
)}
</Modal>
);
}
Example #3
Source File: ConfirmModal.tsx From Shopping-Cart with MIT License | 6 votes |
ConfirmModal = (
title: string,
onOk: VoidCallback,
onCancel?: VoidCallback,
content?: string,
) => {
const { confirm } = Modal;
return confirm({
title,
content,
onOk,
onCancel,
okButtonProps: { type: 'danger' },
});
}
Example #4
Source File: DebugCHQueries.tsx From posthog-foss with MIT License | 6 votes |
export async function debugCHQueries(): Promise<void> {
const results = await api.get('api/debug_ch_queries/')
Modal.info({
visible: true,
width: '80%',
title: 'ClickHouse queries recently executed for this user',
icon: null,
content: (
<>
<Table
columns={[
{ title: 'Timestamp', render: (item) => dayjs(item.timestamp).fromNow() },
{
title: 'Query',
render: function query(item) {
return (
<pre className="code" style={{ maxWidth: 600, fontSize: 12 }}>
{item.query}
</pre>
)
},
},
{
title: 'Execution duration (seconds)',
render: function exec(item) {
return <>{Math.round((item.execution_time + Number.EPSILON) * 100) / 100}</>
},
},
]}
dataSource={results}
size="small"
pagination={false}
/>
</>
),
})
}
Example #5
Source File: App.tsx From dnde with GNU General Public License v3.0 | 6 votes |
function App() {
return (
<StoreProvider>
<HashRouter
getUserConfirmation={async (message, callback) => {
const userConfirm = await new Promise<boolean>((resolve) => {
Modal.confirm({
title: message,
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
callback(userConfirm);
}}
>
<div className="my-app">
<Pages />
</div>
</HashRouter>
</StoreProvider>
);
}
Example #6
Source File: DefaultModal.tsx From html2sketch with MIT License | 6 votes |
ModalPage: FC = () => {
const { elements, ref, setElements } = useElements();
useEffect(() => {
const modal = document.getElementsByClassName('ant-modal')?.item(0);
if (modal) {
setElements([modal]);
}
}, [ref.current]);
return (
<TestLayout elements={elements}>
<div ref={ref} style={{ position: 'relative', minHeight: 400 }}>
<Modal
visible
title="Modal 测试"
mask={false}
// centered
maskClosable
wrapClassName={styles.wrapper}
getContainer={false}
>
这是里面的内容
</Modal>
</div>
</TestLayout>
);
}
Example #7
Source File: FormModal.tsx From yforms with MIT License | 6 votes |
FormModal = (props: YFormModalProps) => {
const AntdConfig = React.useContext(ConfigContext);
const {
children,
formFooter = [
{ type: 'submit', componentProps: { reverseBtns: true, spaceProps: { noStyle: true } } },
],
formProps,
...rest
} = props;
const { onCancel } = rest;
const prefixCls = AntdConfig.getPrefixCls('');
return (
<Modal {...rest} footer={null} bodyStyle={{ padding: 0 }}>
{/* YForm onCancel 无 e ,这里暂时给 null */}
<YForm onCancel={() => onCancel(null)} {...formProps}>
<div className={`${prefixCls}-modal-body`}>
<YForm.Items>{children}</YForm.Items>
</div>
<div className={`${prefixCls}-modal-footer`}>
<YForm.Items>{formFooter}</YForm.Items>
</div>
</YForm>
</Modal>
);
}
Example #8
Source File: DeleteConfirmModal.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
export function DeleteConfirmModal(
props: DeleteConfirmModalProps
): React.ReactElement {
const { t } = useTranslation(NS_BASIC_BRICKS);
const contentTemplate = () => {
return props.message ? (
<div>{props.message}</div>
) : (
<div>
确定删除<span style={{ color: "#FC5043" }}> {props.name} </span>?
</div>
);
};
useEffect(() => {
if (props.visible) {
Modal.confirm({
title: props.title,
content: contentTemplate(),
okText: "确定",
okType: "danger",
onOk: props.handleConfirm,
cancelText: "取消",
onCancel: props.handleCancel
});
}
}, [props.visible]);
return <div></div>;
}
Example #9
Source File: QrcodeModal.tsx From yugong with MIT License | 6 votes |
QrcodeModal:React.FC<Props & ModalProps> = ({sourceData,options={}, canvasClass,info,...other}) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
canvasRef.current && QRCode.toDataURL(canvasRef.current, sourceData, options)
}, [options, sourceData])
return (
<Modal {...other} footer={null}>
<div className={s.root}>
<div className={s.canvaswrap}>
<canvas className={classNames(s.canvas, canvasClass)} ref={canvasRef} />
</div>
{info ? <div>{info}</div> : null}
</div>
</Modal>
)
}
Example #10
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
FormModal = (props: FormModalProps) => {
const { formProps, isEditing, title, loading, ...rest } = props;
const [locale] = useLocaleReceiver('FormModal');
React.useEffect(() => {
return () => {
formProps.form && formProps.form.reset();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const displayTitle = props.exactTitle
? title
: isEditing
? `${replaceMessage(locale.editForm, { label: title as string })}`
: `${replaceMessage(locale.newForm, { label: title as string })}`;
return (
<Modal title={displayTitle} {...rest}>
<Spin spinning={!!loading}>
<Form {...formProps} />
</Spin>
</Modal>
);
}
Example #11
Source File: BasicLayout.tsx From react_admin with MIT License | 5 votes |
{ confirm } = Modal
Example #12
Source File: access.tsx From shippo with MIT License | 5 votes |
{ confirm } = Modal
Example #13
Source File: table.tsx From generator-earth with MIT License | 5 votes |
export default function (props: ITableProps4List) {
const { CONTAINER_ROUTE_PREFIX } = useContext(BaseContext);
const pagination = useTablePagination(props);
const columns: ColumnProps<ITableRecord>[] = [
{
title: '编号',
dataIndex: 'assetCode',
key: 'assetCode'
}, {
title: '名称',
dataIndex: 'assetName',
key: 'assetName'
}, {
title: '主体',
dataIndex: 'contract',
key: 'contract'
}, {
title: '时间',
dataIndex: 'contractDate',
key: 'contractDate'
}, {
title: '创建时间',
dataIndex: 'createDate',
key: 'createDate'
}, {
title: '操作',
key: 'action',
render: (text, record) => (
<Link to={`${CONTAINER_ROUTE_PREFIX}/item/${record.id}`}>查看/修改</Link>
)
}, {
title: '操作',
key: 'action',
render: (text, record) => {
return <a onClick={()=>{onDelete(record.id)}} >删除</a> ;
}
},
];
const onDelete = (id) => {
Modal.confirm({
title: '确定要删除吗?',
onOk: async () => {
// 换成真实删除请求
// await this.props.deleteRecord(id)
console.log('deleting...', id);
// 重新刷新table
await props.updateTable();
},
onCancel() {},
});
};
return (
<Table className="ui-background clearfix"
title={()=>''}
rowKey={record=>record.id}
dataSource={props.tableData.dataSource}
columns={columns}
{...pagination}
/>
);
}
Example #14
Source File: InfoModal.tsx From Shopping-Cart with MIT License | 5 votes |
InfoModal = (type: ModalTypes, title: string, content: string) => {
return Modal['warn']({
title,
content,
});
}
Example #15
Source File: AppEditorLink.tsx From posthog-foss with MIT License | 5 votes |
export function AppEditorLink({
actionId,
style,
children,
}: {
actionId?: number
style?: React.CSSProperties
children: React.ReactNode
}): JSX.Element {
const [modalOpen, setModalOpen] = useState(false)
const { currentTeam } = useValues(teamLogic)
return (
<>
<Button
href={appEditorUrl(currentTeam?.app_urls?.[0], actionId)}
style={style}
size="small"
onClick={(e) => {
e.preventDefault()
setModalOpen(true)
}}
>
{children}
</Button>
<Modal
visible={modalOpen}
title={
actionId
? 'Choose the domain on which to edit this action'
: 'Choose the domain on which to create this action'
}
footer={<Button onClick={() => setModalOpen(false)}>Close</Button>}
onCancel={() => setModalOpen(false)}
>
<AuthorizedUrlsTable actionId={actionId} pageKey="app-editor-link" />
</Modal>
</>
)
}
Example #16
Source File: index.tsx From RareCamp with Apache License 2.0 | 5 votes |
{ confirm } = Modal
Example #17
Source File: index.tsx From antdp with MIT License | 5 votes |
UploadGrid: React.FC<Props> = memo(
({ onChange: onFileChange, useDragHandle = false, ...props }) => {
const [previewImage, setPreviewImage] = useState('');
const fileList = props.fileList || [];
const onSortEnd = ({ oldIndex, newIndex }: SortEnd) => {
onFileChange({ fileList: arrayMove(fileList, oldIndex, newIndex) });
};
const onChange = ({ fileList: newFileList }: UploadChangeParam) => {
onFileChange({ fileList: newFileList });
};
const onRemove = (file: UploadFile) => {
const newFileList = fileList.filter((item) => item.uid !== file.uid);
onFileChange({ fileList: newFileList });
};
const onPreview = async (file: UploadFile) => {
await imagePreview(file, ({ image }) => {
setPreviewImage(image);
});
};
return (
<>
<SortableList
useDragHandle={useDragHandle}
// 当移动 1 之后再触发排序事件,默认是0,会导致无法触发图片的预览和删除事件
distance={1}
items={fileList}
onSortEnd={onSortEnd}
axis="xy"
helperClass="SortableHelper"
props={props}
onChange={onChange}
onRemove={onRemove}
onPreview={onPreview}
/>
<Modal
visible={!!previewImage}
footer={null}
onCancel={() => setPreviewImage('')}
bodyStyle={{ padding: 0 }}
>
<img style={{ width: '100%' }} alt="" src={previewImage} />
</Modal>
</>
);
},
)
Example #18
Source File: index.tsx From XFlow with MIT License | 5 votes |
CreateRelationModal = (props: Props) => {
const { visible, sourceEntity, targetEntity, onOk, onCancel } = props
const [confirmLoading, setConfirmLoading] = useState<boolean>(false)
const [form] = Form.useForm()
const handleOK = () => {
form.validateFields().then(values => {
setConfirmLoading(true)
const cb = () => {
setConfirmLoading(false)
}
onOk({ ...values, cb })
})
}
return (
<Modal
title="关联模型"
visible={visible}
confirmLoading={confirmLoading}
wrapClassName="create-relation-container"
okText="确定"
cancelText="取消"
onOk={handleOK}
onCancel={onCancel}
mask={false}
centered
destroyOnClose={true}
>
<Form form={form}>
<Form.Item
{...formItemLayout}
name="SOURCE_GUID"
label="SOURCE_GUID"
rules={[{ required: true }]}
initialValue={`${sourceEntity?.entityName || ''}(${sourceEntity?.entityId || ''})`}
>
<Input />
</Form.Item>
<Form.Item
{...formItemLayout}
name="TARGET_GUID"
label="TARGET_GUID"
rules={[{ required: true }]}
initialValue={`${targetEntity?.entityName || ''}(${targetEntity?.entityId || ''})`}
>
<Input />
</Form.Item>
<Form.Item
{...formItemLayout}
name="RELATION_TYPE"
label="选择关联关系"
rules={[{ required: true }]}
initialValue={'N:1'}
>
<Select placeholder="请选择关联关系">
<Select.Option value="N:1">多对一</Select.Option>
<Select.Option value="1:N">一对多</Select.Option>
</Select>
</Form.Item>
</Form>
</Modal>
)
}
Example #19
Source File: DepartmentDialog.tsx From graphql-ts-client with MIT License | 5 votes |
DepartemntDialog: FC<{
listFilter: Variables,
value?: ModelType<typeof DEPARTMENT_EDITING_INFO>,
onClose: () => void
}> = memo(({listFilter, value, onClose}) => {
const [form] = useForm<Partial<DepartmentInput>>();
const [merge, merging] = useTypedMutation(DEPARTMENT_MERGE_MUTATION);
useEffect(() => {
if (value === undefined) {
form.setFieldsValue({id: UUIDClass.generate()});
} else {
form.setFieldsValue({
id: value.id,
name: value.name
});
}
}, [value, form]);
const updater = useCallback((store: RecordSourceSelectorProxy<OperationResponseOf<typeof DEPARTMENT_MERGE_MUTATION>>) => {
sharedUpdater(store, listFilter, value);
}, [listFilter, value]);
const onOk = useCallback(async () => {
let input: DepartmentInput;
try {
input = await form.validateFields() as DepartmentInput;
} catch (ex) {
console.log("DepartmentDialog validation error");
return;
}
merge({
variables: {
input,
},
onCompleted: response => {
onClose();
},
onError: () => {
Modal.error({
type: "error",
content: `Failed to ${value === undefined ? "create" : "update"} department`
})
},
optimisticResponse: {
mergeDepartment: {
id: input.id,
name: input.name,
employees: []
}
},
optimisticUpdater: updater,
updater
});
}, [form, merge, onClose, value, updater]);
const onCancel = useCallback(() => {
onClose();
}, [onClose]);
return (
<Modal
visible={true}
title={`${value !== undefined ? 'Modify' : 'Create'} department`}
onOk={onOk}
onCancel={onCancel}
okButtonProps={{loading: merging}}>
<Form form={form}>
<Form.Item name="id" hidden={true} preserve={true}/>
<Form.Item name="name" label="Name" rules={[{required: true, message: 'Name is required'}]}>
<Input autoComplete="off"/>
</Form.Item>
</Form>
</Modal>
);
})
Example #20
Source File: index.ts From brick-design with MIT License | 5 votes |
confirmModal = (fnBsn: () => void) =>
Modal.confirm({
title: '你确定要删除此项吗?',
onOk() {
fnBsn();
},
})
Example #21
Source File: demo3.tsx From yforms with MIT License | 5 votes |
Demo: React.FC<RouteComponentProps> = () => {
const [visible, setVisible] = useState(false);
const handleCancel = () => {
console.log('Clicked cancel button');
setVisible(false);
};
const onFinish = async (values: any) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo);
};
return (
<>
<Button type="link" onClick={() => setVisible(true)}>
打开弹窗
</Button>
<Modal
visible={visible}
maskClosable
destroyOnClose
onCancel={handleCancel}
footer={null}
bodyStyle={{ padding: 0 }}
title="弹窗表单"
>
<YForm
onFinish={onFinish}
onFinishFailed={onFinishFailed}
onCancel={handleCancel}
params={{ type: 'create' }}
>
<YForm.Items className="ant-modal-body">
{[{ type: 'input', name: 'age', label: '姓名' }]}
</YForm.Items>
<YForm.Items className="ant-modal-footer">
{[
{
type: 'submit',
componentProps: { reverseBtns: true, spaceProps: { noStyle: true } },
},
]}
</YForm.Items>
</YForm>
</Modal>
</>
);
}
Example #22
Source File: GeneralModal.spec.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
describe("GeneralModal", () => {
it("should work", () => {
const props = {
visible: true,
configProps: {
title: "default",
width: 1000,
},
modalTitle: "title",
};
const wrapper = shallow(<GeneralModal {...props} />);
wrapper.setProps({ enableFooterSlot: true });
expect(wrapper.find(Modal).length).toBe(1);
});
it("custom button style should work", () => {
const props = {
visible: true,
configProps: {
title: "default",
width: 1000,
okType: "danger",
okText: "SomeOkText",
},
okDisabled: true,
hideCancelButton: true,
modalTitle: "title",
titleIcon: {
icon: "plus",
lib: "antd",
},
};
const wrapper = mount(<GeneralModal {...props} />);
// wrapper类加上display: none实现的隐藏取消按钮,所以还是2个Button
expect(wrapper.find("Button").length).toBe(2);
expect(wrapper.find("Modal").prop("className")).toBe("wrapper");
expect(wrapper.find("Button").at(1).prop("type")).toBe("danger");
expect(wrapper.find("Button").at(1).prop("disabled")).toBeTruthy();
expect(wrapper.find("Button").at(1).find("span").text()).toBe("SomeOkText");
wrapper.setProps({ okDisabled: false });
expect(wrapper.find("Button").at(1).prop("disabled")).toBeFalsy();
expect(wrapper.find(".ant-modal-title").text()).toBe("default");
expect(wrapper.find(".anticon").length).toBe(1);
});
it("should work in fullscreen mode", () => {
const props = {
visible: true,
modalTitle: "title",
fullscreen: true,
};
const spyOnAddEventListener = jest.spyOn(window, "addEventListener");
const spyOnRemoveEventListener = jest.spyOn(window, "removeEventListener");
const wrapper = mount(<GeneralModal {...props} />);
expect(
wrapper
.find(Modal)
.prop("wrapClassName")
.split(" ")
.includes("fullscreen")
).toBe(true);
expect(spyOnAddEventListener).toBeCalledWith("resize", expect.anything());
const handler = spyOnAddEventListener.mock.calls.find(
([type, handler]) => type === "resize"
)[1];
wrapper.setProps({ visible: false });
expect(spyOnRemoveEventListener).toBeCalledWith("resize", handler);
expect(wrapper.find(Modal).length).toBe(1);
});
});
Example #23
Source File: handleHttpError.spec.tsx From next-core with GNU General Public License v3.0 | 5 votes |
spyOnModalError = jest.spyOn(Modal, "error")
Example #24
Source File: CreateProject.tsx From yugong with MIT License | 5 votes |
{ confirm } = Modal
Example #25
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
ConfirmDelete = (props: IProps) => {
const {
deleteItem,
hasTriggerContent = true,
confirmTip,
children,
onConfirm = noop,
title,
secondTitle,
modalChildren,
disabledConfirm = false,
onCancel = noop,
} = props;
const [isVisible, setIsVisible] = React.useState(!hasTriggerContent);
const showModal = () => {
setIsVisible(true);
};
const onOk = () => {
setIsVisible(false);
onConfirm();
};
const cancel = () => {
setIsVisible(false);
onCancel();
};
const _title = title || firstCharToUpper(i18n.t('common:confirm to delete the current {deleteItem}', { deleteItem }));
const _secondTitle =
secondTitle || i18n.t('common:{deleteItem} cannot be restored after deletion. Continue?', { deleteItem });
const _confirmTip =
confirmTip || i18n.t('dop:Delete the {deleteItem} permanently. Please operate with caution.', { deleteItem });
return (
<div>
{hasTriggerContent && (
<>
{confirmTip !== false && <div className="text-desc mb-2">{_confirmTip}</div>}
<span onClick={showModal}>
{children || <Button danger>{i18n.t('common:delete current {deleteItem}', { deleteItem })}</Button>}
</span>
</>
)}
<Modal
title={
<div className="flex flex-wrap items-center">
<ErdaIcon type="tishi" size="20" className="mr-1" color="warning" />
{_title}
</div>
}
visible={isVisible}
onCancel={cancel}
footer={[
<Button key="back" onClick={cancel}>
{i18n.t('Cancel')}
</Button>,
<Button key="submit" type="primary" onClick={onOk} disabled={disabledConfirm}>
{i18n.t('OK')}
</Button>,
]}
>
<p className="mb-2">{_secondTitle}</p>
{modalChildren}
</Modal>
</div>
);
}