React Router(v4)导航栏

1995年

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

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

我的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-结合我传递的道具和反应路由器传递的道具

// 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路由器<NavLink>代替<Link>

<NavLink>是的特殊版本,<Link>当其与当前URL匹配时,会将样式属性添加到呈现的元素。

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

例如,基本导航如下所示:

<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是在活动时提供元素的类。对于本示例,我选择它为selected默认情况下,在react-router v4中,活动状态的给定类为active

<NavLink>在React-Router v4文档中找到更多信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章