Prompt 文档 https://reactrouter.com/core/api/Prompt
Prompt相关问题 https://github.com/ReactTraining/react-router/issues/4635
message
string
function
when: boolean,true则直接跳转
import { Prompt } from 'react-router-dom';<Promptwhen={formIsHalfFilledOut}message="Are you sure you want to leave?"/><Prompt message="Are you sure you want to leave?" /><Promptmessage={(location, action) => {if (action === 'POP') {console.log("Backing up...")}return location.pathname.startsWith("/app")? true: `Are you sure you want to go to ${location.pathname}?`}}/><Prompt when={formIsHalfFilledOut} message="Are you sure?" />
Prompt 跳转其他路由前弹窗询问,场景:
- 某个页面表单有信息输入或变更,用户未保存要离开该页面时,自定义提示用户提示,
- 如果用户确认离开则跳转到新页面,否则留在当前页

浏览器的window.confirm方法,缺点:不支持该方法样式的自定义
import { Prompt } from 'react-router-dom';render(){return(<Prompt message="确定要离开?" when={true}/>)}
window.confirm
阻塞页面,等待用户操作后异步处理页面跳转,router变更
getUserConfirmation方法是浏览器默认的window.prompt
该方法需要写在BrowserRouter 或 MemoryRouter 上
const getConfirmation = (message, callback) => {const allowTransition = window.confirm(message);callback(allowTransition);}<BrowserRouter getUserConfirmation={getConfirmation} />
自定义 modal提示
prompt自定义
- getUserConfirmation
- history.block ```jsx import { Modal } from ‘antd’;
// 重要的callback方法,可以异步执行 function getConfirmation(message, callback) { // G.pageChangeConfirm为页面内的全局变量,用于数据交互与条件判断 if (!G.pageChangeConfirm) { callback(true); return; }
Modal.confirm({ title: ‘离开该页面,表单信息将不被保留?是否确定离开该页面?’, content: ‘’, okText: ‘离开’, cancelText: ‘取消’, onOk() { callback(true); }, onCancel() { callback(false); }, }); }
ReactDOM.render((
<a name="7e2682c4"></a>## form表单验证当需要跳转路由时Prompt的组件 when属性为true 就会提示对应的message<br />等待状态改变后在执行跳转,因为setState是异步的所以要将跳转逻辑放的回调函数中```jsximport React, { useState } from 'react';import { Prompt } from 'react-router-dom';function App() {const [visible, setVisible] = useState(false)function onClick() {setVisible(state => !state)}// 点击弹窗确认function onSubmit(e) {e.preventDefault();setVisible(false)props.history.push('/detail/23')};return (<div><Prompt when={visible} message={location => (`Are you sure you want to go to ${location.pathname}?`)}/><Button type="primary" onClick={onClick}>去详情页</Button></div>)}
