2

我有一个反应路由系统,以及一个包装系统的布局组件。我试图弄清楚如何找出在我的布局组件中选择了哪个路由组件

ReactDOM.render(
<BrowserRouter>
    <Layout>

            <Switch>
                <Route exact strict path={"/home"} component={home} />
                <Route exact path={"/page1"} component={page1} />
                <Route exact path={"/page2"} component={page2} />
                <Route exact path={"/page3"} component={page3}/>
                <Route exact path={"/page4"} component={page4}/>

            </Switch>

    </Layout>
    </BrowserRouter>
,document.getElementById('root'));

this.props.children.selectedRoute有没有办法按照我的方式做一些事情, Layout Component然后返回组件名称?

4

2 回答 2

1

Layout里面BrowserRouter,这确实是可能的。

您所要做的就是将Layout组件包装在withRouter高阶组件中。

export default withRouter(Layout)

然后,在里面Layout你可以访问路由器道具,位置

function Layout({ location }) {
  if(location.pathname==="page1") {
    // Do something
  } else {
    // Other cases
  }
}
于 2018-12-29T19:47:57.767 回答
0

BrowserRouterinreact-router-dom使用 React 上下文将路由器上下文向下传递到组件树。

了解查看的路由的一种简洁方法是Layout挂钩到提供的路由器上下文。您可以通过如下声明组件的contextTypes属性来做到这一点Layout

class Layout extends React.Component {
  static contextTypes = {
    router: PropTypes.object
  };

  render() {
    // Get the current path
    const { route: { location: { pathname } } } = this.context.router;
    const { children } = this.props;

    // Find child route that match current path.
    // This assumes that all routes are current children of the Layout, 
    // with a Switch use `children.props.children` instead of `children`
    // to find the selected route.
    const selectedRoute = children
                           .filter(route => route.props.path === pathname)
                           .pop();
    // continue play.

    return <div>{children}</div>
  }
于 2018-12-29T20:06:26.827 回答