【问题标题】:Custom Prompt component in react-router-dom. Preventing the page reloadingreact-router-dom 中的自定义提示组件。防止页面重新加载
【发布时间】:2020-03-24 17:56:08
【问题描述】:

我正在使用 react-router-dom 中的提示来创建我的自定义组件,以防止用户从弹出表单中离开。

const SignUpForm = () => {

  const { fields, onChange, onSubmit } = useFormState();

  const isEmpty = Object.keys(fields).length === 0;

  usePreventReload(!isEmpty);

  const promptMessage = useMemo(() => JSON.stringify({ fields }), [fields]);

  return (
    <form
      onSubmit={onSubmit}
      noValidate
      autoComplete="off"
    >
      <h2>Sign Up</h2>
      <Prompt when={!isEmpty} message={promptMessage} />
      <TextField
        label="First Name"
        name="firstName"
        onChange={onChange}
      />
        ...

      <Button type="submit" variant="contained" color="secondary">
        Send
      </Button>
    </form>
  );
};

如果您没有在表单中输入任何内容,则可以毫无问题地关闭弹出窗口。当您在任何字段中填写一些值然后尝试关闭弹出窗口时,您将看到一个自定义弹出窗口,其中警告您可能会丢失数据。 除了一种情况 - 页面重新加载之外,它工作得很好。为此,我使用了监听器“beforeunload”,但在这种情况下我们只能使用系统对话框。但是在这种情况下是否也可以使用自定义组件?

我创建了一个简单的演示让您更好地理解 - https://sin9k.com/custom-prompt

有人知道这种情况的解决方法吗?

【问题讨论】:

    标签: javascript reactjs react-router react-router-dom


    【解决方案1】:

    您可以捕获窗口事件“beforeUnload”以在本机上执行此操作,如下所示

    所以在 componentDidMount 中添加这个事件监听器就像

    window.addEventListener('beforeunload', this.pageRefreshFunction);
    

    然后在 componentWillUnmount 中你可以移除这个事件监听器,因为当用户访问其他页面时你不想把它留在那里

     window.removeEventListener('beforeunload', this.pageRefreshFunction);
    

    然后 pageRefreshFunction 应该有你的弹出触发器

    但是根据自定义弹出下方的资源不再允许,您只能使用本机浏览器特定的弹出窗口

    https://developers.google.com/web/updates/2016/04/chrome-51-deprecations#remove_custom_messages_in_onbeforeunload_dialogs

    https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event

    【讨论】:

    • 谢谢,正如我所想。自定义组件是不可能的
    猜你喜欢
    • 2018-01-13
    • 2018-08-31
    • 2022-06-28
    • 1970-01-01
    • 2020-12-10
    • 2021-03-27
    • 2019-01-18
    • 2018-10-14
    • 2022-09-23
    相关资源
    最近更新 更多