【问题标题】:How to create optional parameter on path and activestyle in react router v4/react-router-dom?如何在反应路由器 v4/react-router-dom 中创建路径和活动样式的可选参数?
【发布时间】:2017-11-11 12:01:47
【问题描述】:

我想在我的路由上传递一个可选参数,这是我的代码在根组件中不起作用,过滤器是可选的,我试过 /(: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>

【问题讨论】:

    标签: javascript reactjs react-router-v4 react-router-dom


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-02
        • 2018-09-26
        • 2019-06-15
        • 1970-01-01
        • 2017-08-07
        • 1970-01-01
        • 2018-01-10
        • 2021-06-30
        相关资源
        最近更新 更多