繁体   English   中英

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

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

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

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

然后我需要使用包装函数将其导出,如下所示:

export default withWrapper(MainExperienceComponent);

问题是我想在withWrapper内部withWrapper一个道具。 更具体地说,我想要这样: withWrapper(MainExperienceComponent, prop.id) ,因为withWrapper有两个参数。 这个怎么做?

您可以将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,因此我不确定这是否能回答您的问题。 让我知道我是否误会了。

暂无
暂无

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

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