将位置传递给BrowserRouter的子组件 - React Router

3

I have the following code:

  <BrowserRouter>
    <IndexComponent />
  </BrowserRouter>

在我内部,我有一个包含所有路由的开关。

IndexComponent.js:

<Switch >
  <Route exact path="/course_info/:id" component={CourseInfoPage} />
    <Route exact path="/"  component={Main} />
    .
    .
    .
</Switch>

我想要在IndexComponent中访问位置属性,以便像这样添加过渡动画:
<CSSTransition key={location.key} classNames="fade" timeout={300}>
  <Switch location={location}>
    <Switch >
      <Route exact path="/course_info/:id" component={CourseInfoPage} />
        <Route exact path="/"  component={Main} />
        .
        .
        .
    </Switch>
  </CSSTransition>
</TransitionGroup>

正如您所见,我需要在IndexComponent内部使用location属性。但是它并不存在。为什么呢?我应该如何添加它?

1
这可能会对你有所帮助 https://dev59.com/a1cP5IYBdhLWcg3wr74G#44009788 - Shubham Khatri
1个回答

3

我认为将位置属性传递下去的唯一方法是使用<Route />

  <BrowserRouter>
    <Route render={(props) => <IndexComponent location={props.location}/> }> </Route>
  </BrowserRouter>

然后执行。
<CSSTransition key={this.props.location} classNames="fade" timeout={300}>

或者使用 withRouter HOC,不过简单地使用 <Route component={IndexComponent} /> 也可以。 - Shubham Khatri
@ShubhamKhatri 如果你使用 <Route component={IndexComponent} />,那么你不应该使用 component 而是使用 render,这样你就可以访问 match location history 等属性了。 - Omar
使用 component,所有的 props 都将被传递到 IndexComponent,如果你使用 render,则会在回调中返回 props,你可以选择性地将其传递给组件。然而,如果需要传递一些自定义 props,则通常会使用 render。你可以查看这个链接:https://dev59.com/M1cP5IYBdhLWcg3wiqZr#44255850 - Shubham Khatri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接