reactjs - 如何从侧边栏或导航中的 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}
将Link
s中的 替换为juicyfruit
?如果此侧边栏位于component
我Route
知道我可以查看的位置,this.props.match
但由于侧边栏是独立的,它无法访问match
.
解决方案
从父组件传递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)...
推荐阅读
- embedded-linux - Yocto PREMIRROR/SOURCE_MIRROR_URL 可能带有 url 参数(SAS_TOKEN)?
- json - 从 jq 生成表格输出
- javascript - 正则表达式接受任何值,但在 javascript 中的最大长度为 200
- android - 如何动态强制小部件向右移动?
- excel - 计算空单元格的动态范围
- javascript - Vue 将文本从动态创建的组件复制到剪贴板
- python - 如何使用 discord.py v1.4.1 制作天气命令
- swift - 无法将“String”类型的值分配给“[String]”类型
- android - 使用 libresolv 进行 Android NDK DNS 解析
- javascript - 如何使用javascript在列表中设置活动元素并做出反应?