为了账号安全,请及时绑定邮箱和手机立即绑定

React 如何知道父组件有多少个子组件?

React 如何知道父组件有多少个子组件?

牛魔王的故事 2023-01-06 11:19:55
如果我尝试使用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  ...
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

React.Children.count 方法将帮助您获得所需的内容。

const Navbar = ({ children }) => {
    child_count = React.Children.count(children)
}

https://reactjs.org/docs/react-api.html#reactchildren


查看完整回答
反对 回复 2023-01-06
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信