React-Router <Prompt> 的使用

Prompt 文档
Prompt 示例

  • 使用场景:在离开页面之前,需要判断当前编辑的内容是否已经保存,如果没保存,则弹出提示框,提示用户保存。

  • 查看 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>
  );
}
posted @ 2022-04-15 13:40  shellon  阅读(1688)  评论(0编辑  收藏  举报