首页 > 解决方案 > 如何从侧边栏或导航中的 React Router 获取活动参数值以创建链接?

问题描述

我可能会错误地处理这个问题,但我正在关注React Router 文档中的这个示例。就我而言,侧边栏的其中一个链接需要在其中包含一个嵌套参数(例如/bubblegum/:brand/nutrition),以便我的侧边栏看起来更像这样:

<ul style={{ listStyleType: "none", padding: 0 }}>
  <li>
    <Link to="/">Home</Link>
  </li>
  <li>
    <Link to="/bubblegum">Bubblegum</Link>
  </li>
{brand &&
<>
  <li>Selected Gum: {brand}</li>
  <li>
     <Link to="/bubblegum/{brand}/nutrition">Nutritional Information</Link>
  </li>
  <li>
     <Link to="/bubblegum/{brand}/history">History</Link>
  </li>
</>
}
  <li>
    <Link to="/shoelaces">Shoelaces</Link>
  </li>
</ul>

如果用户导航到/bubblegum/juicyfruit/nutrition如何{brand}Links中的 替换为juicyfruit?如果此侧边栏位于componentRoute知道我可以查看的位置,this.props.match但由于侧边栏是独立的,它无法访问match.

标签: reactjsreact-routerreact-router-v4

解决方案


从父组件传递this.props.match到侧边栏组件...

<Sidebar brand={this.props.match.params.brand}
  ...

或使用withRouter()https://reacttraining.com/react-router/core/api/withRoutermatch )直接将道具动态添加到组件中:

// import withRouter
import { withRouter } from "react-router";

// in your render function of Sidebar component you now have access to `match`
const { match } = this.props;

// use it in your JSX
<li>
  <Link to={`/bubblegum/${match.params.brand}/history`}>History</Link>
</li>

// using `withRouter` requires wrapping your export
export withRouter(Sidebar)...

推荐阅读