-
使用場景:在離開頁面之前,需要判斷當前編輯的內容是否已經保存,如果沒保存,則彈出提示框,提示用戶保存。
-
查看 API 文檔
【總結】:Prompt 有兩個屬性:message
-當用戶離開頁面時給出的提示信息,when
-是否渲染,設置為 true 時,離開頁面時總會渲染,設置為 false 時,離開頁面時不會渲染。我們就可以利用when
設置渲染的時機,當用戶對頁面內容進行編輯,且未保存時離開,設置when=true
,其他情況設置when=false
。
-
代碼
import { Button, Form, Input, Modal } from "antd";
import { useState } from "react";
import { Prompt, useHistory } from "react-router-dom";
export default function PromptDemo() {
const history = useHistory();
const [form] = Form.useForm();
const [isPrompt, setPrompt] = useState(false);
const handlePrompt = () => {
if (!isPrompt) {
return true;
}
Modal.confirm({
title: "未保存",
content: "當前內容未保存,確認退出嗎?",
onOk: () => {
setPrompt(false);
history.goBack();
}
});
return false;
};
const onFinish = (values: any) => {
setPrompt(false);
console.log(values);
};
return (
<div style={{ width: "300px", padding: "40px" }}>
<Prompt when={isPrompt} message={handlePrompt} />
<Form form={form} labelCol={{ span: 6 }} onFinish={onFinish}>
<Form.Item label="姓名" name="name">
<Input onChange={() => setPrompt(true)} />
</Form.Item>
<Form.Item label="手機號" name="mobile">
<Input onChange={() => setPrompt(true)} />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
保存
</Button>
<Button
htmlType="button"
style={{ marginLeft: "24px" }}
onClick={() => history.goBack()}
>
返回
</Button>
</Form.Item>
</Form>
</div>
);
}