[英]Is this.props.children is different for <Route> than other React Components?
Every react component is passed through the following function, found in node_modules ReactElement.js: 每个react组件都通过以下函数传递,该函数位于node_modules ReactElement.js中:
ReactElement.createElement = function (type, config, children){
.
.
.
}
This also Includes <Route>
and <Router>
. 这也包括
<Route>
和<Router>
。 Consider the following JSX Code from a React Tutorial : 考虑一下React教程中的以下JSX代码:
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={Featured} />
<Route path="Settings" component={Settings} />
<Route path="Archives" component={Archives} />
</Route>
</Router>
The above code will be transpiled into the code shown below using Babel : 上面的代码将使用Babel转换为以下所示的代码:
"use strict";
React.createElement(
Router,
{ history: hashHistory },
React.createElement(
Route,
{ path: "/", component: Layout },
React.createElement(IndexRoute, { component: Featured }),
React.createElement(Route, { path: "Settings", component: Settings }),
React.createElement(Route, { path: "Archives", component: Archives })
)
);
From this code, the "children" of the outer <Route>
are the inner 3 <Route>s
. 根据此代码,外部
<Route>
的“子级”是内部3个<Route>s
。 We know that : 我们知道 :
<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>
class MyContainer extends React.Component{
render(){
return (
.
.
//This will be MyFirstComponent or MySecondComponent
{this.props.children}
.
.
);
}
}
But the same is not true for the <Route>s
. 但是对于
<Route>s
却并非如此。 The value of this.prop.children
for the JSX Router code applies to the component
prop, but not the Router itself. JSX路由器代码的
this.prop.children
的值适用于component
prop,但不适用于路由器本身。 Why is this behavior of this.props.children different for <Route>
than any other ReactComponent? 为什么
<Route>
的this.props.children的行为与其他任何ReactComponent都不同?
Because Router deletes its Route children's children. 因为路由器删除了其路由子代的子代。
Here's the createRouteFromReactElement
function from RouteUtils.js
in react-router 3.0.1: 这是react-router 3.0.1中
RouteUtils.js
的createRouteFromReactElement
函数 :
export function createRouteFromReactElement(element) {
const type = element.type
const route = createRoute(type.defaultProps, element.props)
if (route.children) {
const childRoutes = createRoutesFromReactChildren(route.children, route)
if (childRoutes.length)
route.childRoutes = childRoutes
delete route.children
}
return route
}
Notice the line fifth from the end: delete route.children
. 注意最后一行的第五行:
delete route.children
。
Why does it do that? 为什么这样做呢? Consider this invariant warning from
Route.prototype.render
: 考虑一下来自
Route.prototype.render
不变警告:
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.