使用React-Router的#createElement在本地传递道具

时间:2016-12-29 17:40:08

标签: javascript reactjs react-router

docs开始,参数Componentprops来自何处?

// default behavior
function createElement(Component, props) {
  // make sure you pass all the props in!
  return <Component {...props} />
}

如果没有React-Router,本地道具会像这样传递给一个组件:

const myProp="prop";
<ExampleComponent myProp={myProp} />

如何使用React-Router和createElement完成此操作?你会在路由器文件中创建自己的createElement函数吗?

const myProp="prop";
function createElement(Component, myProp) {
  // make sure you pass all the props in!
  return <Component {...myProp} />
}

那么myProp会传递给所有组件吗?

1 个答案:

答案 0 :(得分:1)

一般来说,您不需要提供createElement道具。默认行为将采用您传递给component的{​​{1}}道具并进行渲染。

来自<RouterContext> source

<Route>

在渲染功能中,createElement(component, props) { return component == null ? null : this.props.createElement(component, props) } render() { if (components) { element = components.reduceRight((element, components, index) => { // ... return this.createElement(components, props) }) } return element } components <Route>(或component)道具。 components是组件中injected的道具,例如位置和任何路径参数。

如果要修改匹配的路径组件的呈现方式,则只需提供此prop。例如,如果要将每个路径的组件包装在props组件中,则可以创建以下<Wrapper>函数。

createElement