与 React-Router 的活动链接? [英] Active link with React-Router?

查看:26
本文介绍了与 React-Router 的活动链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试用 React-Router (v4),但在从导航开始让 Link 之一处于 active 时遇到了问题.如果我点击任何 Link 标签,那么活动的东西就会开始工作.但是,我希望 Home Link 在应用程序启动后立即处于活动状态,因为这是在 / 路线上加载的组件.有没有办法做到这一点?

这是我当前的代码:

const Router = () =>(<浏览器路由器><div><导航><Link activeClassName='is-active' to='/'>Home</Link>{/* 我希望它开始时处于活动状态 */}<Link activeClassName='is-active' to='/about'>关于</Link></导航><Match pattern='/' 完全匹配 component={Home}/><Match pattern='/about' 完全匹配 component={About}/><Miss component={NoMatch}/>

</BrowserRouter>)

解决方案

不再具有 activeClassNameactiveStyle 属性.在 react-router v4 中,您必须使用 如果你想做条件样式:

const Router = () =>(<浏览器路由器><div><导航><NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink><NavLink activeClassName='is-active' to='/about'>关于</NavLink></导航><Match pattern='/' 完全匹配 component={Home}/><Match pattern='/about' 完全匹配 component={About}/><Miss component={NoMatch}/>

</BrowserRouter>)

我在主页 中添加了一个精确的属性,我很确定没有它,主页链接将始终处于活动状态,因为 / 将匹配/about 以及您拥有的任何其他页面.

I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

解决方案

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

这篇关于与 React-Router 的活动链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆