页面上顶部导航栏,要实现1.点击到哪个就哪个高亮 2.刷新页面时可以定位到对应高亮页面的导航。
用react要实现类似的操作,主要就是用currentTarget定位到currentIndex,通过判断currentIndex在哪个元素实现切换。
实现思路:
1.点击高亮
给元素添加一个index标志位,然后点击的时候,把这个index用event.currentTarget.getAttribute('index')取出来,然后去设置currentIndex的值,再写一写css的active样式就搞定了。
2.刷新页面时定位到对应导航高亮显示
此处主要用到了react的钩子函数componentDidMount和获取页面地址window.location.pathname,当页面元素加载完成后,将页面路径信息转化为对应导航的下标,然后去设置currentIndex的值,这样指定页面对应的导航item就高亮显示了
页面完整代码如下:
js部分:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import phoneIcon from '../../../statics/img/phone-icon.png';
import { getSourceType } from '@/api/common'
import {
MainHeader,
Placeholder,
HeaderWrapper,
HeaderNav,
Logo,
HeaderRight
} from './style';
class Header extends Component {
constructor(props) {
super(props)
this.state = {
currentIndex: 0
}
this.setCurrentIndex = this.setCurrentIndex.bind(this)
}
componentDidMount (){
// 指定当前页面对应的头部导航高亮显示
let currentPage = window.location.pathname
let navLinkArr = ['/', '/sellcar', '/price', '/aboutus', '/cooperation'];
let currentPageIndex = this.getCurrentIndex(navLinkArr,currentPage)
this.setState({
currentIndex: +currentPageIndex
})
}
getCurrentIndex = ((arr,item)=>{
for(var i in arr){
if(arr[i] === item){
return i;
};
};
});
setCurrentIndex(event) {
console.log('event===',event)
console.log('event.currentTarget===',event.currentTarget)
this.setState({
currentIndex: parseInt(event.currentTarget.getAttribute('index'), 10)
})
}
render() {
getSourceType().then(response => {
console.log(response)
console.log(response.info)
}).catch((err) => {
console.log('err===')
console.log(err)
})
let navArr = ['首页', '我要卖车', '快速估价', '关于我们', '商务合作'];
let navLinkArr = ['/', '/sellcar', '/price', '/aboutus', '/cooperation'];
let itemList = [];
for(let i = 0; i < navArr.length; i++) {
itemList.push(
<Link to={navLinkArr[i]} key={i} index={i} onClick={this.setCurrentIndex}>
<div
className={["nav-title", this.state.currentIndex === i?"nav-active":null].join(' ')}
>{navArr[i]}</div>
</Link>
);
}
return (
<MainHeader>
<HeaderWrapper>
<HeaderNav>
<Link to='/' index='0' onClick={this.setCurrentIndex}>
<Logo/>
</Link>
<HeaderRight>
{itemList}
<Link to='/contactus'>
<div className='nav-title'>
<img className='phone-icon' alt='联系我们' src={phoneIcon}/>
95787
</div>
</Link>
</HeaderRight>
</HeaderNav>
</HeaderWrapper>
<Placeholder></Placeholder>
</MainHeader>
);
}
}
const mapStateToProps = (state) => {
return {
}
}
const mapDispathToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispathToProps)(Header);
css部分:
.nav-title {
padding: 20px 0 12px;
margin: 0 20px;
color: #fff;
font-size:14px;
font-family:Microsoft YaHei;
font-weight:400;
color:rgba(255,255,255,1);
opacity:0.7;
.phone-icon {
width: 20px;
vertical-align: text-bottom;
margin-right: 16px;
}
}
.nav-title:hover {
opacity: 1;
}
.nav-active {
border-bottom: 4px solid #fff;
color:rgba(255,255,255,1);
opacity:1;
}
参考信息:react实现点击选中的li高亮
如有疑问,不吝赐教,感谢!