如何使用react router dom用详细项目组件替换目录组件?

时间:2018-12-29 19:11:48

标签: reactjs react-router-dom

我有一个主要组件,可以使用路由在主要组件之间进行切换。

html, body {
  background-image: url("http://getwallpapers.com/wallpaper/full/e/9/4/629789.jpg");
  height: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

@media screen and (max-width:1024px){
  html, body {
  background-attachment:fixed;
}
}

目录组件基本上是商店中可用项目的列表。当用户单击其中一个项目时,我想用显示该项目及其所有详细信息的组件替换目录组件。当我在详细页面上时,URL应该是我所在的类别,并在其后附加项目名称。

例如-我可能在 / catalog / mens / shirts / brown 上,当我单击某项时,我将被发送到- / catalog / mens / shirts / brown / brown / nameOfShirt 。我可以通过匹配道具获得将用户发送到的网址,但是我为我的DetailsView组件的路径添加了什么?

1 个答案:

答案 0 :(得分:0)

您似乎正在寻找Nested Routing

在主要组件内部,该开关将仅提供着陆和目录视图。

<Switch>
  <Route path="/" exact component={Landing} />
  <Route
    path="/catalog/:category/:type?/:typeOption?"
    component={Catalog}
  />
</Switch>

现在,在目录视图中,您可以使用以下内容嵌套细节:

function Catalog({ match }) {
  return (
    <div>
      <Route
        path={match.path + '/:nameOfProduct'}
        component={DetailedView}
      />
      <Route
        exact
        path={match.path}
        render={() => <h3>Render the list of items here</h3>}
      />
    </div>
  )
}

通过这种方式,URL被修改为附加到之前的内容。

要处理可选参数,您必须以某种方式区分typeproduct的ID。例如。如果我限制所有产品ID都以pr开头,那将是:

<Switch>
  <Route path={`${match.path}/:id(pr.*)`} render={() => <p>Product</p>} />
  <Route path={match.path} render={() => <p>Still Catalogue</p>} />
</Switch>

如果无法使用正则表达式模式区分它们,则必须在URL中添加一个路由参数,使其成为:

/catalog/mens/shirts/product/nameOfShirt /catalog/mens/shirts/type/product/nameOfShirt

这样,您可以在Route语句中为catalog添加Switch