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

如果我尝试使用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

  ...


牛魔王的故事
浏览 117回答 1
1回答

Cats萌萌

React.Children.count 方法将帮助您获得所需的内容。const&nbsp;Navbar&nbsp;=&nbsp;({&nbsp;children&nbsp;})&nbsp;=>&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;child_count&nbsp;=&nbsp;React.Children.count(children) }https://reactjs.org/docs/react-api.html#reactchildren
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript