简体   繁体   中英

Can you add children to WrappedComponent in a Higher-Order Component?

I am trying to implement a HOC that adds a bottom check with Intersection Observer to a component. For that, I need to add a bottom sentinel as a child.

So, inside of the HOC, I need to do:

render () {
 const { children, ...otherProps } = this.props
 return (
  <WrappedComponent {...otherProps}>
   {children}
   <BottomSentinel />
  </WrapperComponent>
}

This is not working. Only the elements defined as children inside WrappedComponent are rendered. BottomSentinel does not appear in DOM.

Can somebody help me? Does adding children in HOCs not work? Is there a better way to do this?

Only the elements defined as children inside WrappedComponent are rendered

Maybe you are missing to render children inside WrappedComponent .

function SomeWrappedComponent({children}) {
    return (
        <>
            <WrappedComponentChildren /> 
            ...
            {children} // You also need to render children inside WrappedComponent
        </>        
    ) 
}

Or what you can do is render children and BottomSentinel outside WrappedComponent

render () {
   const { children, ...otherProps } = this.props
   return (
       <>
           <WrappedComponent {...otherProps} />       
           {children}
           <BottomSentinel /> // rendering outside WrappedComponent 
       </>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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