在卸载 React 组件之前显示警告消息
Show warning message before unmouting React component
我有一个表格。我想在卸载表单组件之前显示警告。
组件是这样的-
import React from "react";
export default function FormComp() {
const sub = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log(formData.get("name"));
//API CALL HERE
};
return (
<div className="test">
<form onSubmit={sub}>
<input name="name" />
<button type="submit">Submit</button>
</form>
</div>
);
}
如果当用户转到不同的路线时组件被卸载,我如何显示一个警告,即表单更改将不会被保存(以及是和否选项)。一旦 FormComp
组件是卸载,表单数据被清除。
您在使用 react-router 吗?这可以很容易。
如果是,那么你可以这样做:
import { Prompt } from 'react-router'
const FormCompComponent = () => (
<>
<Prompt
when={formIsHalfFilledOut}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX here */}
</>
)
有关更多详细信息,请查看:https://v5.reactrouter.com/core/api/Prompt
我有一个表格。我想在卸载表单组件之前显示警告。
组件是这样的-
import React from "react";
export default function FormComp() {
const sub = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log(formData.get("name"));
//API CALL HERE
};
return (
<div className="test">
<form onSubmit={sub}>
<input name="name" />
<button type="submit">Submit</button>
</form>
</div>
);
}
如果当用户转到不同的路线时组件被卸载,我如何显示一个警告,即表单更改将不会被保存(以及是和否选项)。一旦 FormComp
组件是卸载,表单数据被清除。
您在使用 react-router 吗?这可以很容易。
如果是,那么你可以这样做:
import { Prompt } from 'react-router'
const FormCompComponent = () => (
<>
<Prompt
when={formIsHalfFilledOut}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX here */}
</>
)
有关更多详细信息,请查看:https://v5.reactrouter.com/core/api/Prompt