Javascript 如何在 react-router v4 中设置活动链接的样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42044214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:51:35  来源:igfitidea点击:

How can I style active Link in react-router v4?

javascriptreactjsreact-routerreact-router-v4

提问by Ramtin Khalatbari

In react-router v3 we had activeStyle and activeClassName to style active Link

在 react-router v3 中,我们有 activeStyle 和 activeClassName 来设置 active Link 的样式

we could do something like this

我们可以做这样的事情

  <div id="tags-container">
    {tags.map(t =>
      <Link
        className="tags"
        activeStyle={{ color: 'red' }}
        to={t.path}
      >
        {t.title}
      </Link>
    )}
  </div>

I wanna know how can I do same thing in v4?

我想知道如何在 v4 中做同样的事情?

回答by Sergey Reutskiy

Use NavLink instead Link. Its not documented, but its work as you expect. https://github.com/ReactTraining/react-router/issues/4318

使用 NavLink 代替 Link。它没有记录,但它的工作正如你所期望的那样。 https://github.com/ReactTraining/react-router/issues/4318

UPDATE 17.05.2017:

2017 年 5 月 17 日更新:

https://reacttraining.com/react-router/web/api/NavLink

https://reacttraining.com/react-router/web/api/NavLink

回答by Gapur Kassym

You can do it with NavLinkin react-routerv4

你可以NavLinkreact-routerv4 中做到

 <div id="tags-container">
   {tags.map(t =>
     <NavLink
       className="tags"
       activeStyle={{ color: 'red' }}
       to={t.path}
     >
       {t.title}
     </NavLink>
   )}
 </div>

回答by agm1984

If you are encountering an issue where your Nav menu works except it's not updating properlywhen you click links and the route changes, but it works fine if you press F5, you can do this:

如果您遇到导航菜单工作的问题,在您单击链接和路线更改时它没有正确更新,但如果您按 F5,它可以正常工作,您可以执行以下操作:

This is probably occurring because you are using Redux which has a shouldComponentUpdateLifecycle method on its connectfunction. You probably have your Nav component wrapped in connect. This is all good. shouldComponentUpdateis what is ruining your life.

这可能是因为您使用的是 Redux,shouldComponentUpdate它的connect功能上有一个Lifecycle 方法。您可能将 Nav 组件包装在connect. 这一切都很好。shouldComponentUpdate是什么毁了你的生活。

To fix, just bring the router into your mapStateToPropsfunction:

要修复,只需将路由器带入您的mapStateToProps功能:

// This lets shouldComponentUpdate know that the route changed,
// which allows the Nav to re-render properly when the route changes, woot!
const mapStateToProps = (state) => {
  return {
    router: state.router,
  }
}

// or, if you prefer pro style destructure shorthand:
const mapStateToProps = ({ router }) => ({ router })

If you aren't quite sure where state.routercomes from, it comes from the file you combine your reducers in, and you will see something like this:

如果您不太确定state.router来自哪里,它来自您将减速器组合到其中的文件,您将看到如下内容:

import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
import authReducer from './components/auth/auth_reducer'

export default combineReducers({
  router: routerReducer,
  auth: authReducer,
})

Here is some HTML and CSS for a pretty baller Nav Link:

这里有一些 HTML 和 CSS 用于漂亮的芭蕾导航链接:

HTML

HTML

<ul id="Nav_menu">
  <li>
    <NavLink
      to="/home"
      className="Nav_link"
      activeClassName="activeRoute"
      activeStyle={{ color: 'teal' }}
    >
      HOME
    </NavLink>
  </li>
  <li>
    <NavLink
    to="/products"
    className="Nav_link"
    activeClassName="activeRoute"
    activeStyle={{ color: 'teal' }}
    >
      PRODUCTS
    </NavLink>
  </li>
</ul>

NOTE:If you are linking to "/", put exactprop on NavLink.

注意:如果您要链接到"/",请将exact道具放在 NavLink 上。

CSS

CSS

#Nav_menu {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.Nav_link:link {
  color: #fff;
  font-size: 1.6rem;
  line-height: 1.6rem;
  text-decoration: none;
}
.Nav_link:visited {
  color: #fff;
}
.Nav_link:hover {
  color: yellow;
}
.Nav_link:active {
  color: teal;
}

.activeRoute {
  background-color: yellow;
  border-bottom: 0.4rem solid teal;
  cursor: not-allowed;
}

Notice activeStylein the HTML markup. This was the only way I could change the color of the text on the active route/link. It didn't work when I put color: teal;in the activeRouteCSS Class. Open this in another tab: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md

请注意activeStyleHTML 标记中的内容。这是我可以更改活动路线/链接上文本颜色的唯一方法。它不工作,当我把color: teal;activeRouteCSS类。在另一个选项卡中打开它:https: //github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/NavLink.md

If you don't know why I used reminstead of px. This is a great opportunity for you to research web accessibility and base font-size: 10px;.

如果你不知道我为什么用rem而不是px. 这是您研究 Web 可访问性和基础font-size: 10px;.

Stay fit and have fun.

保持健康,玩得开心。

回答by MrSegFaulty

Expanding on @agm1984's answer: The solution of NavLinks is not updating styles correctly, which was using routerReducerfrom react-router-redux, has not worked for me. Instead, I found out that the issue was that connectwrapper uses shouldComponentUpdateand prevented rerendering of the component containing NavLinks.

扩展@agm1984 的回答NavLinks 的解决方案没有正确更新样式,使用routerReducerfrom 的方法react-router-redux对我不起作用。相反,我发现问题在于connect包装器使用shouldComponentUpdate并阻止了包含 NavLink 的组件的重新渲染。

Correct solution in my situation was to pass options object to connectas 4th parameter as shown below:

在我的情况下,正确的解决方案是将选项对象connect作为第 4 个参数传递,如下所示:

export default connect(mapStateToProps, null, null, { pure: false })(NavItems);

回答by glennreyes

This example from the react-router v4 custom link documentationwill help you to accomplish it:

react-router v4自定义链接文档中的这个示例将帮助您完成它:

const OldSchoolMenuLink = ({ label, to, activeOnlyWhenExact }) => (
  <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
    <div className={match ? 'active' : ''}>
      {match ? '> ' : ''}<Link to={to}>{label}</Link>
    </div>
  )}/>
);

So in your case you could create following component:

因此,在您的情况下,您可以创建以下组件:

const CustomLink = ({ activeStyle, children, className, to, activeOnlyWhenExact }) => (
  <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
    <Link to={to} className={className} style={match && activeStyle}>{children}</Link>
  )}/>
);

And then use it like:

然后像这样使用它:

  <div id="tags-container">
    {tags.map(t =>
      <CustomLink
        className="tags"
        activeStyle={{ color: 'red' }}
        to={t.path}
      >
        {t.title}
      </CustomLink>
    )}
  </div>

回答by Alisher Musurmonv

All still works the same. However, react-router-dom v4 replace Linkwith NavLink

一切仍然一样。但是,react-router-dom v4 替换LinkNavLink

import { NavLink as Link } from 'react-router-dom';is also fine. Note: Navlinks by default is active so you can style a:activeor activeStyle={{color: 'red'}}

import { NavLink as Link } from 'react-router-dom';也不错。注意:默认情况下,导航链接处于活动状态,因此您可以设置样式a:activeactiveStyle={{color: 'red'}}