react v4中 props传递

2017-10-16  本文已影响511人  流动码文
WX20171016-225928@2x.png

如上图,react-router v4 组件props中的match等信息是怎么传递下去的呢?

首先在root.js中这样写

const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
);

在 app.js 中这样写

  render() {
    return (
      <div>
        <Switch>
          {
            routes.map((route, index) => (
              <PrivateRoute
                key={index}
                path={route.path}
                exact={route.exact}
                component={route.render}
              />
            ))
          }
        </Switch>
      </div>
    );
  }
}

其实,v4中路由也是组件,普通这样写只match等信息只能在根层组件也就是app.js拿到,路由里面的其它组件根本获取不到,所以,我们只能编写一个privateRoute 传递props;

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => {
    return <Component {...props} />
  }} />
);

export default PrivateRoute;

然后在路由配置文件里将props传递下去

const route = [{
  path: '/home',
  exact: true,
  render: props => < Home {...props} />
}, {
  path: '/chat/:id',
  exact: true,
  render: props => < Chat {...props} />
}];

export default route;

props就是这样从最上级传递到路由的组件中啦。

上一篇下一篇

猜你喜欢

热点阅读