reactjs – React Router(v4)Navbar

我正在使用react-router-dom的v4

我需要在导航栏组件中访问this.props.match,以便我可以设置活动类.我正在使用react-materialize.在< NavItem>中标签,我想添加className = {this.props.match? ‘主动’:”}.但是,我似乎无法访问该比赛.每次我在控制台中打印时,Props都是一个空对象.

我的Nav.js

<Navbar brand='Fuzic' href="/" className="orange darken-3" right>
  <NavItem className={this.match ? 'active' : ''} href="/devices">Devices</NavItem>
  <NavItem><Link to="/devices">Media</Link></NavItem>
  <NavItem><Link to="/devices">Alarms</Link></NavItem>
  <NavItem><Link to="/devices">Interrupts</Link></NavItem>
  <NavItem><Link to="/auth">Admin</Link></NavItem>
</Navbar>

我的App.js

<browserRouter>
  <div>
    <Nav/>
    <div className="container">
      <Switch>
        <PropsRoute exact path="/" component={Auth}/>
        <PropsRoute exact path="/devices" component={Devices} devices={this.state.devices} setCurrentDevice={this.setCurrentDevice} />
        <PropsRoute path="/devices/:deviceid" component={Detail} currentDevice={this.state.currentDevice} />
        <PropsRoute path="/auth" component={Auth}/>
        <PropsRoute component={NotFound}/>
      </Switch>
    </div>
  </div> 
</browserRouter>

helper.js – 结合我传递的道具&从react-router传递的道具

// Exerp From:  https://github.com/ReactTraining/react-router/issues/4105
export const renderMergedProps = (component,...rest) => {
  const finalProps = Object.assign({},...rest);
  return (
    React.createElement(component,finalProps)
  );
}

export const PropsRoute = ({ component,...rest }) => {
  return (
    <Route {...rest} render={routeProps => {
      return renderMergedProps(component,routeProps,rest);
    }}/>
  );
}

大多数在线文档和文章都适用于v2和3. v4的文档没有详细说明如何处理这个问题.许多人为他们的应用程序嵌套了一条路线.但是,当我这样做时,我在控制台中获得了一个堆栈溢出框架的打印.

我如何解决这个问题,以便获得匹配的访问权限?

在Nav组件上,尝试使用react router’s< NavLink>而不是< Link>.

< NavLink>是< Link>的特殊版本这将在渲染元素与当前URL匹配时将样式属性添加到渲染元素.

< NavLink>具有activeClassName和activeStyle属性,您可以使用它们将样式应用于活动导航项.

例如,基本导航将是这样的:

<nav>
    <NavLink activeStyle={{color: 'red'}} to="/foo">Foo</NavLink>
    <NavLink activeStyle={{color: 'red'}} to="/bar">Bar Group</NavLink>
    <NavLink activeStyle={{color: 'red'}} to="/another-foo">Another Foo</NavLink>
    <NavLink activeStyle={{color: 'red'}} to="/another-bar">Another Bar</NavLink>
</nav>

其中activeStyle表示在元素处于活动状态时应用于该元素的样式.

并通过activeClassName在同一个示例下面:

<nav>
    <NavLink activeClassName="selected" to="/foo">Foo</NavLink>
    <NavLink activeClassName="selected" to="/bar">Bar Group</NavLink>
    <NavLink activeClassName="selected" to="/another-foo">Another Foo</NavLink>
    <NavLink activeClassName="selected" to="/another-bar">Another Bar</NavLink>
</nav>

activeClassName是在元素处于活动状态时为其提供的类.对于这个例子,我选择它来选择它.认情况下,react-router v4给定类的活动状态是活动的.

了解有关< NavLink>的更多信息在react-router v4 documentation

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...