[英]Injecting/passing components as props from HOC to the Wrapped-Component
In my recent React project I have used some HOC's to pass component as props to the wrappedcomponent and I was wondering if there is anything thing wrong with this approach. 在我最近的React项目中,我使用了一些HOC将组件作为道具传递给包装的组件,我想知道这种方法是否有什么问题。 Below is an example:
下面是一个示例:
HOC: HOC:
import AnotherComponent from './a'
function withExampleComponent(WrappedComponent){
render(){
const exampleComp = <ExampleComponent someprops={value} />
return(
<WrappedComponent {...this.props} exampleComponent={exampleComp} />
)
}
}
And here is the component that uses the above HOC 这是使用上述HOC的组件
class MainComponent extends React.Component{
render(){
const {exampleComponent} = this.props
return(
<div>
{exampleComponent}
</div>
)
}
}
export default withExampleComponent(MainComponent)
Thank you 谢谢
in withExampleComponent you are missing to return a component definition. 在withExampleComponent中,您缺少返回组件定义的信息。 According react site https://reactjs.org/docs/higher-order-components.html .
根据反应站点https://reactjs.org/docs/higher-order-components.html 。 you should return something like
你应该返回类似
import AnotherComponent from './a'
function withExampleComponent(WrappedComponent){
return class extends React.Component {
render(){
const exampleComp = <ExampleComponent someprops={value} />
return(
<WrappedComponent {...this.props} exampleComponent={exampleComp} />
)
}
}
}
and to use with MainComponent 并与MainComponent一起使用
export default withExampleComponent(MainComponent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.