dev*_*l69 5 javascript reactjs react-router-dom page-transition
我了解到,使用react-router-dom v5,可以使用该<Prompt>组件在页面转换发生之前询问用户,以便用户可以阻止它。
现在,他们暂时从 v6 中删除了它(计划“稍后”有一个强大的实现)。相反,他们建议您自己实现一个等效的组件……我现在就想这样做。
但是:我发现没有办法真正阻止react-router-dom v6中的页面转换。有人知道吗?
您可以,但它需要使用自定义history对象和HistoryRouter. 因为这history@5需要是一个包依赖项。
导入版本 5 的history.
npm i -S history@5
Run Code Online (Sandbox Code Playgroud)
创建并导出自定义history对象。
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
Run Code Online (Sandbox Code Playgroud)
导入并渲染 aHistoryRouter并history作为 prop 传递。
...
import { unstable_HistoryRouter as Router } from "react-router-dom";
import history from './history';
...
<Router history={history}>
<App />
</Router>
Run Code Online (Sandbox Code Playgroud)
请遵循阻止转换的文档。
Run Code Online (Sandbox Code Playgroud)// Block navigation and register a callback that // fires when a navigation attempt is blocked. let unblock = history.block((tx) => { // Navigation was blocked! Let's show a confirmation dialog // so the user can decide if they actually want to navigate // away and discard changes they've made in the current page. let url = tx.location.pathname; if (window.confirm(`Are you sure you want to go to ${url}?`)) { // Unblock the navigation. unblock(); // Retry the transition. tx.retry(); } });
演示:
| 归档时间: |
|
| 查看次数: |
3701 次 |
| 最近记录: |