javascript - react-router 中的模态路由
问题描述
我尝试像在反应路由器示例中那样实现模态路由器,但它在使用时有效,Link
但在我尝试使用时不起作用history.push
。我正在尝试通过以编程方式导航来实现多级模式。检查堆栈闪电战
// This works
<Link
to={{
pathname: `/img/${id}`,
state: { background: location }
}}
>
<Thumbnail color={color} />
<p>{title}</p>
</Link>
// This doesn't
<a href="#" onClick={
() => history.push({
pathname: `/img/${id}`,
state: { background: location }
})
}>
<Thumbnail color={color} />
<p>{title}</p>
</div>
// My Router
<div>
<Switch location={background || location}>
<Route path="/" exact component={Home} />
<Route path="/contacts" exact component={Contacts} />
</Switch>
{background && <Route path="/contact/:name" children={<Modal />} />}
</div>
如何解决此问题以使其在没有Link
标签的情况下工作?使用的代码有什么错误?
解决方案
我认为这可以通过添加 event.preventDefault() 来解决。因为当你点击链接时,整个页面被重新加载并且 history.push() 永远不会执行
<a href="#" onClick={
(e) => {
e.preventDefault()
history.push({
pathname: `/img/${id}`,
state: { background: location }
}})
}>
推荐阅读
- vba - 如何在 VBA for Microsoft word 中使用非 activeX 内容控制器
- aws-lambda - 在批量执行 AWS Kinesis 之前设置超时延迟
- python - 如何使用烧瓶和我的数据库动态生成 URL?
- javascript - 从中心轴旋转/反弹图像
- sql - 围绕列表中的值的案例陈述
- elasticsearch - 在 NiFi 中使用“ScrollElasticSearchHttp”处理器时出错
- node.js - Houd CI 解析错误:“import”和“export”可能只出现在“sourceType:module”中
- windows - “svn ls....”命令是否存在 Windows 等效项?
- reactjs - 复制粘贴 React.js 应用程序时我需要更改什么?
- mysql - 使用节点JS将带有数组的json对象插入到mysql表中