对 useBlocker
的封装,用于向用户显示一个 window.confirm
提示,而不是使用 useBlocker
构建自定义UI。
unstable_
标志不会被移除,因为这项技术有很多不完善之处,并且如果用户在确认框打开时点击额外的后退/前进导航,它在不同浏览器中的行为会非常不同(有时会不正确)。请自行承担使用风险。
function ImportantForm() {
let [value, setValue] = React.useState("");
// Block navigating elsewhere when data has been entered into the input
unstable_usePrompt({
message: "Are you sure?",
when: ({ currentLocation, nextLocation }) =>
value !== "" &&
currentLocation.pathname !== nextLocation.pathname,
});
return (
<Form method="post">
<label>
Enter some important data:
<input
name="data"
value={value}
onChange={(e) => setValue(e.target.value)}
/>
</label>
<button type="submit">Save</button>
</Form>
);
}
function usePrompt({
when,
message,
}: {
when: boolean | BlockerFunction;
message: string;
}): void
在确认对话框中显示的消息。
一个布尔值或一个返回布尔值的函数,指示是否阻止导航。如果提供一个函数,它将接收一个包含 currentLocation
和 nextLocation
属性的对象。
无返回值。