【问题标题】:Pass a prop in a Hoc function when this prop is inside the component当这个 prop 在组件内部时,在 Hoc 函数中传递一个 prop
【发布时间】:2018-12-05 12:53:15
【问题描述】:

我知道标题很奇怪,但让我解释一下。我有一个带有道具的组件:

const MainExperienceComponent = props => (
  <div>
    ....
  </div>
);

然后我需要使用这样的包装函数将其导出:

export default withWrapper(MainExperienceComponent);

问题是我想在withWrapper 内部传递一个道具。更具体地说,我想要这个:withWrapper(MainExperienceComponent, prop.id) 所以withWrapper 有两个参数。如何做到这一点?

【问题讨论】:

    标签: javascript reactjs redux components higher-order-functions


    【解决方案1】:

    您可以将MainExperienceComponent 包含在您想要使用它的类中(具有您想要传递的道具的类)并将其分配为实例变量。

    class Container extends Component {
      // inside the constructor:
      constructor(props) {
        super(props)
        this.WrappedComponent = withWrapper(MainExperienceComponent, props.id)
      }
    
      // or outside the constructor:
    
      WrappedComponent = withWrapper(MainExperienceComponent, this.props.id)
    
      render() {
        return (
          // Use <this.WrappedComponent /> here
        )
      }
    }
    

    然后您的 HOC 将接受两个参数:

    const withWrapper(WrappedComponent, id) => {
      ...
    }
    

    这是假设 Container 组件可以访问您要传入的道具。如果您将 id 道具传递给 MainExperienceComponent 组件,那么 HOC 将已经可以访问它。

    调用者:

    const Wrapped = withWrapper(MainExperienceComponent)
    ...
    <Wrapped id={someId} /> // where does someId come from?
    

    HOC:

    const withWrapper = (WrappedComponent) => {
      class NewComponent extends Component {
        // you have access to `this.props.id`
        render() {
          return <WrappedComponent />
        }
      }
    
      return NewComponent
    }
    

    如果是这种情况,则无需将两个参数传递给 HOC,因此我不确定这是否能回答您的问题。如果我误解了,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-25
      • 2019-12-08
      • 2023-01-30
      • 2021-01-27
      • 1970-01-01
      • 2017-04-07
      • 2020-08-05
      • 2020-01-09
      相关资源
      最近更新 更多