react中component 传参问题

我们知道组件传参有个很基本的方式:
定义一个组件:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
在使用的时候,<Welcome name="Sara" />就把Sara传进组件了

我想问的是形如这种,

<Router history={history}>
      <Route path="/" component={MainLayout} />
</Router>

如何传参呢???
阅读 4.9k
2 个回答

不知道我理解的你的问题对不对:

其实你看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);
}

这里本来就不是用来传参的,写在这个组件的父组件的render函数里

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题