“ react ”:“16.8.4”
你好,有人知道如何检查(功能)组件中是否存在子组件(在渲染它们之前)
React.Children.count
React.Children.toArray(children)
不会工作
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>
}
}
如有任何帮助,感激不尽
最佳答案
解决方案一:
获取 child 类型
。如果 Child
组件返回 null,它将返回 null
:
const isChildNull = children => {
return Boolean(children.type()=== null);
};
方案二:
使用 ReactDOMServer.renderToStaticMarkup .它将 jsx
元素转换为 string
。如果 children 返回 null,则 renderToStaticMarkup
将返回一个空字符串:
import ReactDOMServer from 'react-dom/server';
const isChildNull = children => {
return !Boolean(ReactDOMServer.renderToStaticMarkup(children));
};
用法:
const Child = () => {
return null;
};
const Parent = ({ children }) => {
const isNull = isChildNull(children);
if (isNull) {
return "render null";
}
return <div>{children}</div>;
};
export default function App() {
return (
<Parent>
<Child />
</Parent>
);
}
关于javascript - React 组件子项在渲染前检测是否为空/null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55303409/