You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React判断子组件类型时报__docgenInfo不存在于string类型如何解决

报错原因

React.isValidElement 仅能确认child是合法React元素,但此时child.type的类型是string | JSXElementConstructor<any>联合类型:

  • 原生HTML标签对应的type是字符串类型(比如<div>的type就是'div'),不存在__docgenInfo属性
  • 只有自定义组件对应的JSXElementConstructor类型才可能存在DocGen注入的__docgenInfo元信息
    TS检测到string类型上不存在目标属性,因此抛出错误。

解决方案

你只需要将child.type断言为包含你要访问的属性结构的类型即可,无需完整声明所有属性:

const hasButtons = React.Children.toArray(children).some((child) => 
  React.isValidElement(child) && 
  (child.type as { __docgenInfo?: { displayName?: string } })?.__docgenInfo?.displayName === 'Button'
);

如果想要逻辑更严谨,可以先排除type为字符串的原生标签场景,再做断言,避免无意义的判断:

const hasButtons = React.Children.toArray(children).some((child) => {
  if (!React.isValidElement(child)) return false;
  const { type } = child;
  if (typeof type === 'string') return false;
  return (type as { __docgenInfo?: { displayName?: string } })?.__docgenInfo?.displayName === 'Button';
});

额外注意

依赖__docgenInfo的判断方式仅适用于开发环境,这个属性是React DocGen工具注入的元信息,生产环境构建时大概率会被优化移除。如果需要生产环境也可用,建议直接给你的Button组件设置静态displayName属性,改为判断type.displayName === 'Button',兼容性更强。


内容的提问来源于stack exchange,提问作者SomeGuy103

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:54:01