如果我尝试使用 Object.keys(children).length
并且只有 1 个子组件,那么它会给出一个子组件拥有的键数量。此方法仅在存在多个子组件时才有效。如何找到组件拥有的子组件数量?
<Navbar>
<Component 1/>
</Navbar>
const Navbar = ({ children }) => {
console.log(Object.keys(children).length); //displays properly only if more than 1 child component
console.log(children.length); //undefined
...
最佳答案
React.Children.count 方法将帮助您获得所需的内容。
const Navbar = ({ children }) => {
child_count = React.Children.count(children)
}
关于javascript - React 如何知道父组件有多少个子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63400882/