[React Router v4] Style a Link that is Active with NavLink

本文介绍如何使用 React Router v4 中的 NavLink 组件为当前激活的导航链接添加样式。通过三种不同方式设置 activeClassName 或使用 isActive 回调函数实现链接的激活状态判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

We often need to be able to apply style to navigation links based on the current route. In React Router v4 you can easily accomplish this with the NavLink component. In this lesson, we will step through three ways to accomplish styling links through the use of an active class with the NavLink component.

 

There are three ways to check an link is active or not and add active class for it:

const isLinkActive = (match, location) => {
    return match
};

const Nav = () => (
  <nav>
      <NavLink to="/" exact activeStyle={{color: 'pink'}}>Home</NavLink>
      <NavLink to="/about" activeClassName="active">About</NavLink>
      <NavLink replace
               to={{pathname: '/contact'}}
               isActive={isLinkActive}
               activeClassName="active"
      >Contact</NavLink>
  </nav>
);

 

'isActive' prop allows you to decide whether or not to apply active class.

转载于:https://www.cnblogs.com/Answer1215/p/6592585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值