reactjs - 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”,则更容易理解。
解决方案
在此代码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
属性。
推荐阅读
- java - CellStyle 类型中的方法 setFillForegroundColor(short) 不适用于参数 (XSSFColor)
- c# - 通过 IServiceCollection 使用参数注册泛型类型
- mysql - PHP mysql按可空日期字段排序
- c - 为什么 fseek 使用 read() 系统调用?
- ruby-on-rails - Rails 中的语句类已过时?
- java - 如何使用 executeBatch 获取返回值?
- c# - Parallel.Foreach 在 Linux 机器上失败,但在 Windows 机器上工作
- ruby-on-rails - 如何使我的助手代码更苗条?
- c - CPU1 上线失败
- python - 使用 beautifullSoup 从隐藏形式中获取多重价值