目录
问题二: tab 字体的样式默认都为蓝色,如何还原 ant-design-pro 的样式?
问题三:点击文字可以切换,但是点击 tab 的非文字部分不会切换,何解?
1、页面顶部添加 tab,点击切换 tab 时,可切换
import { Tabs } from "antd";
import { useEffect, useState } from "react";
import "./index.less";
const panes = [{
key: "one",
title: "tab1",
},{
key: "two",
title: "tab2",
}]
<div className="header-tabs">
<Tabs
size="large"
type="line"
tabPosition="top"
animated={false}
onChange={handleSwitchPanel}
>
{ panes.map( pane => {
return (
<TabPane
key={ pane.key }
tab={ pane.title }
></TabPane>
);
})}
</Tabs>
</div>
2、将 tab 与路由相关
在上述代码的基础上添加或修改:
// ...
import { Link } from "react-router-dom";
const [currentTab, setCurrentTab] = useState("");
// 获取当前路由
const currentRoute = location.pathname;
const panes = [{
key: "one",
title: "tab1",
path: "/a"
},{
key: "two",
title: "tab2",
path: "/b"
}]
useEffect(() => {
setCurrentTab(currentRoute.split('/')[1])
}, [currentRoute]);
const handleSwitchTab = () => {
if(currentRoute==="/a"){
setCurrentTab("one");
}
if(currentRoute==="/b"){
setCurrentTab("two");
}
}
<div className="header-tabs">
<Tabs
// ...
>
{ panes.map( pane => {
return (
<TabPane
// ...
tab={
<Link
to={
{pathname: pane.path}}
>{ pane.title }</Link>
}
></TabPane>
);
})}
</Tabs>
</div>
3、问题解决
问题一:tab 没有据页面头部水平垂直居中,何解?
问题解决:
<Tabs
// ...
centered={true}
tabBarGutter={100}
tabBarStyle={
{marginBottom: '0px', lineHeight: '18px'}}
>
// ...
</Tabs>
// index.less
.header-tabs {
margin: 0 auto;
padding-left: 100px;
}
问题二: tab 字体的样式默认都为蓝色,如何还原 ant-design-pro 的样式?
问题解析:由于 Link 自动被浏览器编译为一个包含 a 标签的 div,所以字体默为 a 标签的蓝色。
问题解决:
<TabPane
// ...
tab={
<Link
// ...
className={ pane.key === currentTab ? "selected-color" : "default-color" }
>
// ...
</Link>
}
></TabPane>
// index.less
@import '~antd/lib/style/themes/default.less';// 引入官方提供的颜色文件
.headers-tabs {
.select-text-color{
color: @primary-color;// color: rgb(24, 144, 255);
}
.default-text-color{
color: @select-item-selected-color;// color:rgb(105, 103, 103);
}
}
问题三:点击文字可以切换,但是点击 tab 的非文字部分不会切换,何解?
问题分析:
这是由于 TabPane 的 tab 属性嵌套了 Link 所致,Link 被渲染出来的 a 标签,大小只有文字撑开的尺寸,所以,在 Link 上指定的路径,只在文字上有效,只有点击文字才会跳转。
问题解决:
能用 CSS 很快解决的问题不要用 JavaScript。
<Tabs
className="tabs"
// ...
>
{ panes.map( pane => {
return (
<TabPane
tab={
<Link
className="pane_link"
style={
{color: pane.key === proCurTab && 'rgb(24, 144, 255)'}}
// ...
>
//...
</Link>
}
></TabPane>
)
}) }
</Tabs>
// index.less
.headers-tabs{
.tabs{
.ant-tabs-tab{
padding: 0px;
}
.pane_link{
display: block;
padding: 16px 0;
color: @select-item-selected-color;// rgb(105, 103, 103)
}
}
}