简体   繁体   English

当该道具位于组件内部时,在Hoc函数中传递该道具

[英]Pass a prop in a Hoc function when this prop is inside the component

I know the title is weird but let me explain. 我知道标题很奇怪,但让我解释一下。 I have a component with props: 我有一个道具的组成部分:

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

and then I need to export it using a wrapper function like this: 然后我需要使用包装函数将其导出,如下所示:

export default withWrapper(MainExperienceComponent);

The problem is that I want to pass inside the withWrapper a prop. 问题是我想在withWrapper内部withWrapper一个道具。 To be more specific I want this: withWrapper(MainExperienceComponent, prop.id) so as the withWrapper has two args. 更具体地说,我想要这样: withWrapper(MainExperienceComponent, prop.id) ,因为withWrapper有两个参数。 How to do this? 这个怎么做?

You can wrap your MainExperienceComponent within the class you want to use it in (the one that has the props you want to pass) and assign it as an instance variable. 您可以将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
    )
  }
}

Your HOC would then accept two arguments: 然后,您的HOC会接受两个参数:

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

This is assuming that the Container component has access to the props you want to pass in. If you're passing the id prop into the MainExperienceComponent component then the HOC would already have access to it. 这是假设Container组件可以访问您想要传递的道具。如果将id道具传递给MainExperienceComponent组件,那么HOC将已经可以访问它。

the caller: 呼叫者,召集者:

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

the HOC: HOC:

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

  return NewComponent
}

If this was the case, there would be no need for passing two arguments to the HOC so I'm not sure this answers your question. 如果是这种情况,则无需将两个参数传递给HOC,因此我不确定这是否能回答您的问题。 Let me know if I'm misunderstanding. 让我知道我是否误会了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM