Javascript 这是不是.props.children与<;路线>;而不是其他成分?
每个react组件都通过节点_modules ReactElement.js中的以下函数传递:Javascript 这是不是.props.children与<;路线>;而不是其他成分?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,每个react组件都通过节点_modules ReactElement.js中的以下函数传递: ReactElement.createElement = function (type, config, children){ . . . } 这还包括和。从下面的JSX代码中考虑: 根据该代码,外部的“子项”是内部的3个s。我们知道: <MyContainer> <MyFirstComponent /> <MySecondComponent
ReactElement.createElement = function (type, config, children){
.
.
.
}
这还包括
和
。从下面的JSX代码中考虑:
根据该代码,外部
的“子项”是内部的3个s
。我们知道:
<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>
class MyContainer extends React.Component{
render(){
return (
.
.
//This will be MyFirstComponent or MySecondComponent
{this.props.children}
.
.
);
}
}
类MyContainer扩展了React.Component{
render(){
返回(
.
.
//这将是MyFirstComponent或MySecondComponent
{this.props.children}
.
.
);
}
}
但对于
s
,情况并非如此。JSX路由器代码的this.prop.children
值适用于组件
prop,但不适用于路由器本身。为什么
的this.props.children的行为与任何其他组件不同 因为路由器删除其路由子节点的子节点
以下是react路由器3.0.1中的:
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
}
注意末尾的第五行:删除route.children
为什么会这样?考虑这个不变量警告:
render(){
不变的(
假,,
'元素仅用于路由器配置,不应呈现'
)
}
感谢您解释“为什么”。在我接受这个答案之前,请您在react中添加代码,其中this.props.children被分配给路由的组件?@AjayH这看起来像是在的渲染
方法中发生的。
<MyContainer>
<MyFirstComponent />
<MySecondComponent />
</MyContainer>
class MyContainer extends React.Component{
render(){
return (
.
.
//This will be MyFirstComponent or MySecondComponent
{this.props.children}
.
.
);
}
}
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
}
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
)
}