简体   繁体   English

您可以在高阶组件中为 WrappedComponent 添加子组件吗?

[英]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.我正在尝试实现一个 HOC,该 HOC 将使用 Intersection Observer 的底部检查添加到组件中。 For that, I need to add a bottom sentinel as a child.为此,我需要在小时候添加一个底部哨兵。

So, inside of the HOC, I need to do:因此,在 HOC 内部,我需要执行以下操作:

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.仅呈现在 WrappedComponent 中定义为子元素的元素。 BottomSentinel does not appear in DOM. BottomSentinel 不会出现在 DOM 中。

Can somebody help me?有人可以帮助我吗? Does adding children in HOCs not work?在 HOC 中添加孩子不起作用吗? Is there a better way to do this?有一个更好的方法吗?

Only the elements defined as children inside WrappedComponent are rendered仅呈现 WrappedComponent 中定义为子项的元素

Maybe you are missing to render children inside WrappedComponent .也许您缺少在WrappedComponent渲染children 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或者你可以做的是在BottomSentinel之外渲染childrenWrappedComponent

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

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

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