如何正确地将相同的道具传递给多个组件?

时间:2016-12-21 11:34:35

标签: reactjs

我有一个基于其道具的组件,使用几乎相同的道具渲染另一个组件,如下所示:

render() {
  return(
    <Component>
      {this.renderComponent()}
    </Component>
  )


renderComponent() {
  switch (condition) {
    case "A": {
      return (
        <ComponentA
         many={...}
         same={...}
         things={...}
         oneDifferentProp="A"
        />
    }
    case "B": {
      return (
        <WrapperComponent>
          <ComponentB
           many={...}
           same={...}
           things={...}
           oneDifferentProp="B"
          />
          <SomethingOther>
        </WrapperComponent>
      )
    }
  }
}

那么我该如何使其更好,可扩展且易于阅读?

1 个答案:

答案 0 :(得分:8)

您可以在此处使用spread syntax

renderComponent() {
  // Create/pass in this object however you want
  let sharedProps = { many: 1, same: 2, things: 3 }; 

  switch (condition) {
    case "A":
      return (
        <ComponentA
         oneDifferentProp="A"
         {...sharedProps}
        />
      )
    case "B":
      return (
        <WrapperComponent>
          <ComponentB
           oneDifferentProp="B"
           {...sharedProps}
          />
          <SomethingOther />
        </WrapperComponent>
      )
  }
}