react.js - react中component 传参问题
本文介绍了react.js - react中component 传参问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我们知道组件传参有个很基本的方式:
定义一个组件:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
在使用的时候,<Welcome name="Sara" />就把Sara传进组件了
我想问的是形如这种,
<Router history={history}>
<Route path="/" component={MainLayout} />
</Router>
如何传参呢???
解决方案
不知道我理解的你的问题对不对:
其实你看babel
的转义结果就能看出来:
<Router history={history}>
<Route path="/" component={MainLayout} />
<Route path="/a" component={ALayout} />
</Router>
React.createElement(
Router,
{ history: history },
React.createElement(Route, { path: "/", component: MainLayout }),
React.createElement(Route, { path: "/a", component: ALayout })
);
根据文档,可以知道他其实把包含在内部的所有element
当作children
来处理,在Router
中也会被放在this.props.children
里面。而history
还是一样被当作组件的属性传入。
关于createElement
,你或许可以这么想(源码要比这个复杂很多):
function createElement(Component, props, ...children) {
let finalProps = { ...props, children };
return Component(finalProps);
}
这篇关于react.js - react中component 传参问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文