react-router 在路由切換時進行提示


react-router 版本 ^5.1.2

在有正在編輯的內容未保存時,發生了路由切換,此時需要給出一些提示,並由用戶控制是否進行跳轉。

react-router進行路由管理時,可以使用 Prompt 組件實現此功能,其中的message屬性可以接受一個函數,返回string的時候就提示,默認為window.confirm進行提示,用戶可以選擇是否跳轉;返回true的時候就直接路由切換,不進行提示。

可以將Prompt進行簡單的封裝,如下:

import { Prompt} from "react-router-dom";

export default function RouterPrompt ({message,promptBoolean}) {
    // Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
    return  <Prompt message={
                        location =>
                            !promptBoolean
                            ? true
                            : message || '當前頁面有未保存的內容,是否離開?'
                    }
            />
}

使用的時候,哪個組件需要在離開時進行提示,引入一下就行,可以放在組件的任意位置。是否需要提示由使用者自己控制。

            <div className="hardware">
                {/* 這里是根據輸入框的編輯狀態來設置是否需要提示 */}
                <RouterPrompt promptBoolean={EDIT_STATUS}></RouterPrompt>
                {/* 其他內容 */}
            </div>

提示默認使用的是window.confirm,但還可以通過getUserConfirmation進行自定義。

import { HashRouter as Router} from "react-router-dom";
import { Modal} from 'antd';

// message 就是window.confirm的message,通過callback控制是否通過
// 這里直接使用antd的Modal組件
customConfirm = (message,callback) => {
    Modal.confirm({
        title:message,
        onCancel: () => {
            callback(false);
            },
            onOk: () => {
            callback(true);
            }
    })
}
<Router getUserConfirmation={customConfirm}></Router>

效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM