React子组件开发:解决TypeScript中'type'属性不存在的类型错误
解决React组件子组件筛选的TypeScript类型错误
错误原因
React.ReactNode 是包含字符串、数字、布尔值、React元素等的联合类型,只有 ReactElement 类型的节点才拥有 type 属性。直接访问 child?.type 会因为其他类型(比如字符串)没有该属性触发TypeScript报错。
解决方案
通过类型守卫先判断子节点是否为合法的React元素,再访问其 type.displayName 属性:
1. 定义类型守卫函数
import type { ReactElement } from 'react'; // 类型守卫:判断节点是否为ReactElement const isReactElement = (child: React.ReactNode): child is ReactElement => { return !!(child && typeof child === 'object' && 'type' in child); };
2. 修改筛选函数
const getChildrenOnDisplayName = (children: React.ReactNode, displayName: string) => { return React.Children.map(children, (child) => { // 先验证节点类型,再匹配displayName if (isReactElement(child) && child.type.displayName === displayName) { return child; } return null; }); };
简化写法(无需单独类型守卫)
如果不想额外定义类型守卫,也可以直接在函数内做类型判断:
const getChildrenOnDisplayName = (children: React.ReactNode, displayName: string) => { return React.Children.map(children, (child) => { if (child && typeof child === 'object' && 'type' in child && child.type.displayName === displayName) { return child; } return null; }); };
额外注意事项
确保你的子组件(如 Modal.Header、Modal.Body)正确设置了 displayName,否则筛选逻辑会失效:
// 示例:给Modal.Header设置displayName Modal.Header = ({ children }: { children: React.ReactNode }) => { return <div>{children}</div>; }; Modal.Header.displayName = 'Header';
内容的提问来源于stack exchange,提问作者Salvador Bacci
相关产品推荐
相关产品推荐

