【问题标题】:Modal routes in react-routerreact-router 中的模态路由
【发布时间】:2021-10-26 11:42:45
【问题描述】:

我尝试在react router example 中实现模态路由器,但与Link 一起使用时它可以工作,但当我尝试使用history.push 时它不起作用。我正在尝试通过以编程方式导航来实现多级模式。检查stack-blitz

// 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 标签的情况下解决此问题?使用的代码有什么错误?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      相关资源
      最近更新 更多