React Router Prompt 覆盖

问题描述 投票:1回答:1

我用的是 React Router Prompt 如果表格填了一半,就禁止导航到另一个路径。

一切都很正常,但是 Prompt 抛出默认的浏览器确认框。

根据需求,我需要呈现自定义Dilog框。

有谁能给我建议,如何用自定义dilog框覆盖浏览器默认的确认框。

reactjs prompt react-router-v4
1个回答
0
投票

这是一个很好的指南,任何人都可以遇到这个问题 。https:/medium.com@michaelchan_13570using-react-router-v4-prompt-with-custom-modal-component-ca839f5faf39。

注意:如果你不是阻止导航到特定的URL,而是每当有人离开有RouteLeavingGuard的页面时,就会根据提示。在RouteLeavingGuard中调用useHistoryuseLocation,这样一来,你唯一需要考虑的就是当道具

 const [modalVisible, setModalVisible] = useState(false);

  const [lastLocation, setLastLocation] = useState<Location | null>(null);

  const [confirmedNavigation, setConfirmedNavigation] = useState(false);

  const history = useHistory();

  const { pathname } = useLocation();



  const closeModal = (): void => {

    setModalVisible(false);

  };

  const handleBlockedNavigation = (nextLocation: Location): boolean => {

    if (!confirmedNavigation && pathname) {

      setModalVisible(true);

      setLastLocation(nextLocation);

      return false;

    }

    return true;

  };

  const handleConfirmNavigationClick = (): void => {

    setModalVisible(false);

    setConfirmedNavigation(true);

  };

  useEffect(() => {

    if (confirmedNavigation && lastLocation) {

      // Navigate to the previous blocked location with your navigate function

      history.push(lastLocation.pathname);

    }

  }, [confirmedNavigation, history, lastLocation]);
© www.soinside.com 2019 - 2024. All rights reserved.