usePrompt
本页内容

unstable_usePrompt



此 API 是实验性的,可能会在次要/补丁版本中发生重大更改。请谨慎使用,并密切关注相关更改的发行说明。

摘要

参考文档 ↗

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

参数

options.message

在确认对话框中显示的消息。

options.when

一个布尔值或一个返回布尔值的函数,指示是否阻止导航。如果提供一个函数,它将接收一个包含 currentLocationnextLocation 属性的对象。

返回

无返回值。

文档和示例 CC 4.0
编辑