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>
效果如下:
如对本文有疑问, 点击进行留言回复!!
荐 超强的入门文章 !!! JavaScript 速成计划第二篇(杂项详解:JS操作HTML 与 CSS、异常、事件)!
教你搭建 nodejs+mongoose+Graphql+Vue+Typescript 框架(上)
【Nginx】如何为已安装的Nginx动态添加模块?看完我懂了!!
网友评论