好客租房119-tabbar栏目高亮bug修复
路由切换页面高亮的问题
import React from 'react'
import { TabBar } from 'antd-mobile'
import {BrowserRouter as Router,Route, Link} from "react-router-dom"
import News from "../News/index.js"
import Index from "../Index/index.js"
import HouseList from "../HouseList/index.js"
import Profile from "../Profile/index.js"
//导入组件自己的样式文件
// 路由奇幻的时候代码没有覆盖到 不能高亮
//在路由奇幻时候 执行 菜单高亮代码
//钩子函数创建
import "./index.css"
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
// 重定向
selectedTab:this.props.location.pathname,
};
}
//判断路由是否变化
componentDidUpdate(prevProps){
if(prevProps.location.pathname!=this.props.location.pathname){
//此时发生路由切换了
this.setState({
selectedTab:this.props.location.pathname
})
}
}
renderTabBarItem(){
const tabItems=[{
title:"首页",
icon:'icon-ind',
path:"/home/index"
},
{
title:"搜索",
icon:'icon-findHouse',
path:"/home/list"
},
{
title:"资讯",
icon:'icon-infom',
path:"/home/news"
},
{
title:"我的",
icon:'icon-my',
path:"/home/profile"
}
]
return tabItems.map(item=> (
<TabBar.Item
title={item.title}
key={item.title}
icon={
<i className={`iconfont ${item.icon}`}></i>
}
// 选中后的展示图片
selectedIcon={
<i className={`iconfont ${item.icon}`}></i>
}
// 是否选中
selected={this.state.selectedTab === item.path}
// bar 点击触发,需要自己改变组件 state & selecte={true}
onPress={() => {
this.setState({
selectedTab: item.path,
});
//路由切换
this.props.history.push(item.path)
}}
>
{/* // 将 home 组件作为实参传递
{this.renderContent(<Home />)} */}
</TabBar.Item>
)
)
}
render() {
return (
<div className='home'>
<Route path="/home/profile" component={Profile}></Route>
<Route path="/home/list" component={HouseList}></Route>
<Route exact path="/home" component={Index}></Route>
<Route path="/home/news" component={News}></Route>
<TabBar
unselectedTintColor="#21b97a"
tintColor="#33A3F4"
barTintColor="white"
noRenderContent={true}
>
{this.renderTabBarItem()}
</TabBar>
</div>
);
}
}
总结
componentDidUpdate解决当前问题