next.js 导航点击添加样式问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36754767/article/details/89646095

在这里插入图片描述
由于next.js的路由由自带的Link组件实现,并且通过点击无法获取到路由跳转标签,故不能通过点击addClass的方法动态实现添加样式,并且由于next.jsSSR的原因未生成window.document不能引入jquey,解决方法:获取当前路由,判断是否与Link标签路由相同,如果相同则设置样式,代码如下:
首页文件获取当前路由并传递

import React,{Component} from 'react'
import Layout from '../components/Layout'
export default class extends React.Component {


  render() {

    return (
      <Layout url={this.props.url.pathname}>
        <p>这是首页</p>
         </ Layout>
    )
  }
}

Link标签所在组件获取路由,并做判断是否设置样式

 <a     style={{ textDecoration: 'none', width: '100%', height: '26px', display: 'inline-block', textAlign: 'center', fontSize: '13px', lineHeight: '26px',fontWeight:'600',color:(this.props.url==='/')?'white':'black',backgroundColor:(this.props.url==='/')?'#d33333':'none'}} >首页</a>  

关键:

(this.props.url===’/’) this.props.url接收路由,根据路由渲染样式

猜你喜欢

转载自blog.csdn.net/qq_36754767/article/details/89646095