Prompt 文档 https://reactrouter.com/core/api/Prompt
Prompt相关问题 https://github.com/ReactTraining/react-router/issues/4635

message
string
function

when: boolean,true则直接跳转

  1. import { Prompt } from 'react-router-dom';
  2. <Prompt
  3. when={formIsHalfFilledOut}
  4. message="Are you sure you want to leave?"
  5. />
  6. <Prompt message="Are you sure you want to leave?" />
  7. <Prompt
  8. message={(location, action) => {
  9. if (action === 'POP') {
  10. console.log("Backing up...")
  11. }
  12. return location.pathname.startsWith("/app")
  13. ? true
  14. : `Are you sure you want to go to ${location.pathname}?`
  15. }}
  16. />
  17. <Prompt when={formIsHalfFilledOut} message="Are you sure?" />

Prompt 跳转其他路由前弹窗询问,场景:

  1. 某个页面表单有信息输入或变更,用户未保存要离开该页面时,自定义提示用户提示,
  2. 如果用户确认离开则跳转到新页面,否则留在当前页

image.png
浏览器的window.confirm方法,缺点:不支持该方法样式的自定义

  1. import { Prompt } from 'react-router-dom';
  2. render(){
  3. return(
  4. <Prompt message="确定要离开?" when={true}/>
  5. )
  6. }

window.confirm

阻塞页面,等待用户操作后异步处理页面跳转,router变更
getUserConfirmation方法是浏览器默认的window.prompt
该方法需要写在BrowserRouter 或 MemoryRouter 上

  1. const getConfirmation = (message, callback) => {
  2. const allowTransition = window.confirm(message);
  3. callback(allowTransition);
  4. }
  5. <BrowserRouter getUserConfirmation={getConfirmation} />

自定义 modal提示

prompt自定义

  1. getUserConfirmation
  2. 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(( , document.getElementById(‘react-wraper’) );

  1. <a name="7e2682c4"></a>
  2. ## form表单验证
  3. 当需要跳转路由时Prompt的组件 when属性为true 就会提示对应的message<br />等待状态改变后在执行跳转,因为setState是异步的所以要将跳转逻辑放的回调函数中
  4. ```jsx
  5. import React, { useState } from 'react';
  6. import { Prompt } from 'react-router-dom';
  7. function App() {
  8. const [visible, setVisible] = useState(false)
  9. function onClick() {
  10. setVisible(state => !state)
  11. }
  12. // 点击弹窗确认
  13. function onSubmit(e) {
  14. e.preventDefault();
  15. setVisible(false)
  16. props.history.push('/detail/23')
  17. };
  18. return (
  19. <div>
  20. <Prompt when={visible} message={location => (
  21. `Are you sure you want to go to ${location.pathname}?`
  22. )}/>
  23. <Button type="primary" onClick={onClick}>去详情页</Button>
  24. </div>
  25. )
  26. }