首页 > 解决方案 > React 将所有属性收集为一个道具并将其放入组件中吗?

问题描述

我正在从https://reacttraining.com/react-router/web/example/route-config阅读以下代码

const RouteWithSubRoutes = route => (
  <Route
    path={route.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <route.component {...props} routes={route.routes} />
    )}
  />
);

const RouteConfigExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/tacos">Tacos</Link>
        </li>
        <li>
          <Link to="/sandwiches">Sandwiches</Link>
        </li>
      </ul>

      {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
    </div>
  </Router>
);

请看第一行,为什么不是这样:

const RouteWithSubRoutes = ({route}) => (

据我所知,这个箭头函数应该得到一个我们通常称之为props的参数,它应该是一个包含所有放入的属性的集合。在这种情况下,props应该包括'key'和'route'的所有属性.

在箭头函数的组件 RouteWithSubRouters 中,我们应该从集合 props 中过滤有用的属性,例如路由,因此我们将参数写为 ({route})。

我理解错了吗?为什么当我将其更改为 ({route}) 时会显示错误?

==================================================== ==================

谢谢大家!现在我知道参数魔法了。我将代码更改如下:

const RouteWithSubRoutes = (routeProps) => {
    console.log(routeProps.aaa)
    return (
  <Route
    path={routeProps.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <routeProps.component {...props} routes={routeProps.routes} />
    )}
  />
);

const RouteConfigExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/tacos">Tacos</Link>
        </li>
        <li>
          <Link to="/sandwiches">Sandwiches</Link>
        </li>
      </ul>

      {routes.map((route, i) => <RouteWithSubRoutes key={i} aaa="bbb" {...route} />)}
    </div>
  </Router>
);

我得到打印'bbb'〜。如果将参数命名为“props”,则更容易理解。

标签: reactjsreact-router-v4

解决方案


在此代码route中是一个对象,其中包含必须用于创建的值<Route>。由于props名称不明确并且在同一组件中使用,因此可以将其明确定义为:

const RouteWithSubRoutes = routeProps => (
  <Route
    path={routeProps.path}
    render={props => (
      // pass the sub-routes down to keep nesting
      <routeProps.component {...props} routes={routeProps.routes} />
    )}
  />
);

或解构(component需要重命名为大写):

const RouteWithSubRoutes = ({ path, routes, component: Component }) => (
  <Route
    path={path}
    render={props => (
      <Component {...props} routes={routes} />
    )}
  />
);

const RouteWithSubRoutes = ({route}) => (...)将是一个错误,因为接收的routeProps对象RouteWithSubRoutes没有route属性。


推荐阅读