首页 > 解决方案 > 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标签的情况下工作?使用的代码有什么错误?

标签: javascriptreactjsreact-router

解决方案


我认为这可以通过添加 event.preventDefault() 来解决。因为当你点击链接时,整个页面被重新加载并且 history.push() 永远不会执行

<a href="#" onClick={
  (e) => { 
    e.preventDefault()
    history.push({
      pathname: `/img/${id}`,
      state: { background: location }
  }})
}>

推荐阅读