“反应”:“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>
}
}
对于任何帮助,想法感激
原文由 user11243583 发布,翻译遵循 CC BY-SA 4.0 许可协议
解决方案 1:
得到孩子们
type
。它将返回null
如果Child
组件返回 null:解决方案 2:
使用 ReactDOMServer.renderToStaticMarkup 。它将
jsx
元素转换为string
。如果 children 返回 null 那么renderToStaticMarkup
将返回一个空字符串:用法:
使用解决方案 1 的工作示例