tab链接:https://ant.design/components/tabs-cn/
实现思路
- 进入tab页之后,通过
window.location.href获取url,在useEffect中判断url是否包含有tab key,有则使用当前tab key作为route,没有就默认一个值 - 点击
tab时,触发onchange事件,通过window.history.pushState将当前tab的key替换到浏览器地址栏 - 添加事件监听器,当点击浏览器的前进后退时,触发
popstate事件,将最新的url的path传递给tab的activeKey。这样tabs的内容也跟着前进后退的操作改变
项目使用create-react-app创建,App.js直接替换为以下代码即可运行
import React from "react";
import { Tabs } from 'antd'
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
export default function App() {
const { TabPane } = Tabs
const initPath = window.location.href.split('/').pop()
const tabKeys = ['about', 'user', 'home']
const [state,setState] = React.useState( initPath )
React.useEffect( ()=>{
if( !tabKeys.includes( initPath ) ) setState('about')
}, [] )
window.addEventListener("popstate", function(e) {
const curPath = window.location.href.split('/').pop()
setState( curPath )
}, false);
const onTabChanged = (key) => {
setState(key)
window.history.pushState({},'',key); // 或者replace
}
return (
<Tabs tabPosition={'left'} onChange={onTabChanged} activeKey={state}>
<TabPane tab='About' key={tabKeys[0]} >
<About/>
</TabPane>
<TabPane tab='Users' key={tabKeys[1]}>
<Users />
</TabPane>
<TabPane tab='Home' key={tabKeys[2]}>
<Home />
</TabPane>
</Tabs>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}