-
在父组件中可以通过this.props.children访问children,但如果是要遍历children数组需要使用
React.Children.forEach(this.props.children, (node)=>{}) 进行遍历 -
在ts中react.children的类型非常多,可以通过
React.isValidElement(node) 判断是否为 React 元素 -
然后再使用node.type与导入的特定子组件做对比,找出特定组件
-
如果使用了context向下传递数据,而导入的子组件通过contextType获取了该context,在使用子组件做对比的时候就会报错,这种情况下需要将contex层单独分出去一个组件
参考页面
https://stackoverflow.com/questions/56384761/cannot-access-class-contexttype-within-a-child-component
https://stackoverflow.com/questions/55464194/how-to-define-typescript-for-react-children-map