如何使用 react-router <Prompt> 显示组件以防止或允许路由更改

我目前正在尝试找到一种方法来显示自定义组件(如 Modal)以使用该Prompt组件确认路由更改。

Promp组件的默认行为是显示带有消息的确认对话框,如您在此示例中所见:React Router:防止转换。

注意:我正在使用该<BrowserRouter>组件。

路由器有一个propnamed getUserConfirmation,您可以使用它来自定义<Prompt>组件的行为。

// this is the default behavior


function getConfirmation(message, callback) {

  const allowTransition = window.confirm(message);

  callback(allowTransition);

}


<BrowserRouter getUserConfirmation={getConfirmation} />;

我正在尝试做的事情:

  • 父组件APP内部

    • 我将confirm状态设置为 true,以显示<Confirm>组件

    • 我正在尝试callbackgetConfirmation函数从函数传递给<Confirm>组件以调用它true以允许转换,并false阻止它。

    • true or false如上所示,将在默认行为中调用回调。

function getConfirmation(message, callback) {

    console.log("Inside getConfirmation function...");

    setConfirmCallback(callback);

    setConfirm(true);

    // const allowTransition = window.confirm(message);

    // callback(allowTransition);

  }

这是App.js渲染的内容:


return (

    <Router getUserConfirmation={getConfirmation}>

      <AllRoutes />

      {confirm && (

        <Confirm confirmCallback={confirmCallback} setConfirm={setConfirm} />

      )}

    </Router>

  );

似乎是什么问题:

  • confirm对话框似乎在那时阻止了该功能。所以callback变量/参数仍在范围内。所以一切正常。

  • 当我删除confirm对话框时,该函数一直运行。当我点击<Confirm>组件内的确认按钮时,callback不再存在。

问题

有没有人知道使用react-router-dom?


繁华开满天机
浏览 420回答 2
2回答

富国沪深

我为我的案例找到了一个简单的解决方法。我无法分享整个组件,只能分享片段。// this will initiate the dialogbox render and&nbsp;// prevent the window from going back by returning falseconst backButtonPressed = async () => {&nbsp; &nbsp; leavePrompt(false);&nbsp; &nbsp; return false;}// this will open the prompt dialog boxconst leavePrompt = (endRoom) => {&nbsp; &nbsp; setOpenPrompt({open: true, action: endRoom ? "endRoom" : "leaveQuitely"});}// render<Dialog open={openPrompt.open} aria-labelledby="interim-user-dialog-title">&nbsp; &nbsp; <DialogContent dividers>&nbsp; &nbsp; &nbsp; &nbsp; <Typography variant="h6" gutterBottom>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Are you sure?&nbsp; &nbsp; &nbsp; &nbsp; </Typography>&nbsp; &nbsp; </DialogContent>&nbsp; &nbsp; &nbsp; &nbsp; <DialogActions>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Button onClick={() => setOpenPrompt({...openPrompt, open: false})} color="primary">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Stay&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Button onClick={() => history.push("/")} color="secondary">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Leave&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Button>&nbsp; &nbsp; &nbsp; &nbsp; </DialogActions></Dialog>// when allowedToGoBack state is true then call a method that will render the dialog box<Prompt&nbsp; &nbsp; when={true}&nbsp; &nbsp; title={"Alert"}&nbsp; &nbsp; message={() => allowedToGoBack ? backButtonPressed() && false : true}&nbsp;/>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript