方案一:Tabs + Link
import { Tabs } from "antd";
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import Foods from "./components/Foods";
import './index.less';
const { TabPane } = Tabs;
const Header = (props) => {
const {
foods,
match,
} = props
const { fruitsList, vegetablesList } = foods
const { defaultTab } = match.params;
const [currentTab, setCurrentTab] = useState(defaultTab);
const panes = [{
key: "fruits",
title: "水果",
path: `/foods/fruits`,
},{
key: "vegetables",
title: "蔬菜",
path: `/foods/vegetables`,
}]
let foodsList = null;
if(currentTab==="fruits"){
if(fruitsList){
foodsList = fruitsList;
}
}else if(currentTab==="vegetables"){
if(vegetablesList){
foodsList = vegetablesList;
}
}
const handleChange = (key) => {
setCurrentTab(key);
};
return (
<div className="header-tabs">
<Tabs
className="tabs"
size="large"
type="line"
tabPosition="top"
centered={true}
animated={false}
activeKey={currentTab}
tabBarGutter={100}
tabBarStyle={
{marginBottom: '0px', lineHeight: '18px'}}
onChange={handleSwitchPanel}
>
{ panes.map( pane => {
return (
<TabPane
key={ pane.key }
tab={
<Link
className="tab_pane_link"
style={
{color: pane.key===currentTab && 'rgb(24, 144, 255)'}}
to={
{pathname: pane.path}}
>{pane.title}</Link>
}
>
{foodsList ? (
<Foods />
) : ("")}
</TabPane>
);
})}
</Tabs>
</div>
)
}
export default Header;
// index.less
// ...
.header-tabs {
margin: 0 auto;
padding-left: 100px;
.tabs{
.ant-tabs-tab{
padding: 0px;
}
.tab_pane_link{
display: block;
padding: 16px 0;
color: rgb(105, 103, 103);
}
}
}
// ...
实现过程及踩坑,请看:https://blog.csdn.net/mChales_Liu/article/details/112685653