为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁华开满天机 2021-06-29 14:35:24
我目前正在尝试找到一种方法来显示自定义组件(如 Modal)以使用该Prompt组件确认路由更改。Promp组件的默认行为是显示带有消息的确认对话框,如您在此示例中所见:React Router:防止转换。注意:我正在使用该<BrowserRouter>组件。路由器有一个propnamed getUserConfirmation,您可以使用它来自定义<Prompt>组件的行为。// this is the default behaviorfunction getConfirmation(message, callback) {  const allowTransition = window.confirm(message);  callback(allowTransition);}<BrowserRouter getUserConfirmation={getConfirmation} />;我正在尝试做的事情:父组件APP内部我将confirm状态设置为 true,以显示<Confirm>组件我正在尝试callback将getConfirmation函数从函数传递给<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?
查看完整描述

2 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

我为我的案例找到了一个简单的解决方法。我无法分享整个组件,只能分享片段。


// this will initiate the dialogbox render and 

// prevent the window from going back by returning false

const backButtonPressed = async () => {

    leavePrompt(false);

    return false;

}


// this will open the prompt dialog box

const leavePrompt = (endRoom) => {

    setOpenPrompt({open: true, action: endRoom ? "endRoom" : "leaveQuitely"});

}


// render

<Dialog open={openPrompt.open} aria-labelledby="interim-user-dialog-title">

    <DialogContent dividers>

        <Typography variant="h6" gutterBottom>

            Are you sure?

        </Typography>

    </DialogContent>

        <DialogActions>

            <Button onClick={() => setOpenPrompt({...openPrompt, open: false})} color="primary">

                Stay

            </Button>

            <Button onClick={() => history.push("/")} color="secondary">

                Leave

            </Button>

        </DialogActions>

</Dialog>



// when allowedToGoBack state is true then call a method that will render the dialog box

<Prompt

    when={true}

    title={"Alert"}

    message={() => allowedToGoBack ? backButtonPressed() && false : true} 

/>


查看完整回答
反对 回复 2021-07-08
  • 2 回答
  • 0 关注
  • 417 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信