您可以将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,因此我不确定这是否能回答您的问题。如果我误解了,请告诉我。