0

我想在我的路由上传递一个可选参数,这是我的代码在根组件中不起作用,过滤器是可选的,我试过 /(:filter) 它不起作用:

<BrowserRouter>
    <Route path="/:filter?" component={App}/>
</BrowserRouter>

此代码位于我的页脚组件上,该组件使用仅使用 NavLink 的 FilterLink:

const Footer = () => (
  <p>
    Show:
    {" "}
    <FilterLink filter="all"> 
      All 
    </FilterLink>
    {", "}
    <FilterLink filter="active">
      Active
    </FilterLink>
    {", "}
    <FilterLink filter="completed">
      Completed
    </FilterLink>
  </p>
);

它正在工作,但样式仅影响根组件或 localhost:3000/ (根)

 <NavLink 
    to={ filter === 'all' ? '' : filter }
    activeStyle={{
      textDecoration: 'none',
      color: 'black'
    }}
  >
  {children}
  </NavLink>
4

2 回答 2

1

简单地说,您可以将(精确)添加到 NavLink,如下所示:

 <NavLink 
    exact
    to={ filter === 'all' ? '' : filter }
    activeStyle={{
      textDecoration: 'none',
      color: 'black'
    }}
  >
  {children}
  </NavLink>
于 2019-01-19T13:41:50.267 回答
0

您可以只指定另一个没有过滤参数的路由:

<BrowserRouter>
    <Route exact={true} path="/" component={App}/>
    <Route path="/:filter" component={App}/>
</BrowserRouter>
于 2017-06-09T12:59:29.590 回答