从函数返回React组件并提供道具

时间:2019-06-19 19:48:40

标签: reactjs

我有以下方法返回一个Component

const getChildComponent = ({ type }) => {
  let childComponent = null
  switch (type) {
    case 'component_1':
      childComponent = <SomeComponent />
      break;
  }
  return { childComponent }
}

export default getChildComponent

我从下面的单独组件调用上述方法

export default class ParentComponent extends React.Component {
  render() {
    const { component } = getChildComponent({ type })
    return (
      <Container>
        <Content>
          {childComponent} // How to pass props here?
        </Content>
      </Container>
    );
  }
}

是否可以将道具从ParentComponent传递到childComponent(而不必通过getChildComponent()方法传递道具)?

2 个答案:

答案 0 :(得分:3)

返回the component, not the element。换句话说,返回SomeComponent,而不是<SomeComponent/>

const getChildComponent = ({ type }) => {
  switch (type) {
    case 'component_1':
      return SomeComponent;
  }
}

export default class ParentComponent extends React.Component {
  render() {
    const ChildComponent = getChildComponent({ type });
    return (
      <Container>
        <Content>
          <ChildComponent {...props}/>
        </Content>
      </Container>
    );
  }
}

答案 1 :(得分:1)

由于您的getChildComponent函数返回一个React元素而不是实际组件,因此您应该能够使用React.cloneElement将自定义道具传递给子组件。

以下是使用您提供的代码示例的示例。

export default class ParentComponent extends React.Component {
  render() {
    const { component } = getChildComponent({ type })
    return (
      <Container>
        <Content>
          {React.cloneElement(component, { propA: "foobar" })} // pass props to second argument
        </Content>
      </Container>
    );
  }
}