React组件子元件在呈现之前检测是否为空/ null

问题描述 投票:1回答:2

“反应”:“16.8.4”

您好,有人知道如何检查(功能)组件中是否存在子项(在呈现它们之前)

React.Children.count
React.Children.toArray(children)

不会工作

孩子们是$$typeof: Symbol(react.element)

代码示例是

function ContextMenuItems(): JSX.Element | null {
   if (no-items) return null;  
   ...
}

class ContextMenu extends React.Component {
   public render(): JSX.Element | null {
      if (this.props.children === null) { //ContextMenuItems empty check
        return null;
       }
       return <ContextMenu>{this.props.children}</ContextMenu>
   }
}

对于任何帮助,想法感谢

javascript reactjs
2个回答
1
投票

您可以通过阅读子道具来检查组件是否有子项,以及React.Children.count代码将是:

function ContextMenuItems({ children }): JSX.Element | null {
   if (!React.Children.count(children)) return null;
   ...
}

0
投票

我们用钩子做了一个黑客:(

如果您有兴趣并且为了更好地理解,请看一下。

也许有人知道如何优化它,现在它是一个预渲染

https://codesandbox.io/s/x7489l2lo

© www.soinside.com 2019 - 2024. All rights reserved.