Gatsby 是一款基于 React 和 GraphQL 的静态文档生成器。
思路:
获取路由,根据路由显示导航高亮;
this.props.location.pathname 获取路由;
若this.props.location.pathname获取不到值,可用window.location.pathname获取;
// layouts index.js
import React, { Component } from "react"
import PropTypes from 'prop-types'
import Helmet from 'react-helmet' // 设置站点的title
import './reset.css'
import './index.css'
import Header from '../components/header'
import Footer from '../components/footer'
class Layout extends Component {
render() {
const { children } = this.props;
const { location } = window; // 获取路由
return (
<div className='wrapper'>
<Helmet>
<meta charSet="utf-8" />
<title>title</title>
</Helmet>
<div className='content-wrapper'>
<div className='content'>
<Header location={ location }></Header>
<div className='content'>
{children}
</div>
<Footer></Footer>
</div>
</div>
</div>
)
}
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
// components/header.js
// location.pathname获取路由,根据路由导航显示高亮
import React from 'react'
import { Link } from 'gatsby'
import './header.css'
const Header = ({ location }) => (
<header className='header'>
<div className='wrapper'>
<div className='logo-wrapper'>
<div className='img'>
<img src={'/img/logo.png'} alt='logo'/>
</div>
</div>
<div className='nav-list'>
<ul>
<li>
<Link className={location.pathname === "/" ? 'active' : ''} to="/">首页</Link>
</li>
<li>
<Link className={location.pathname.match(/\/About/i) ? 'active' : ''} to="/About/about">关于</Link>
</li>
<li>
<Link className={location.pathname.match(/\/Business/i) ? 'active' : ''} to="/Business/business">业务</Link>
</li>
<li>
<Link className={location.pathname.match(/\/News/i) ? 'active' : ''} to="/News/news">新闻</Link>
</li>
<li>
<Link className={location.pathname.match(/\/Partner/i) ? 'active' : ''} to="/Partner/partner">合作</Link>
</li>
<li>
<Link className={location.pathname.match(/\/Contact/i) ? 'active' : ''} to="/Contact/contact">联系</Link>
</li>
</ul>
</div>
</div>
</header>
)
export default Header