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

React遍历children查找指定className元素时触发未定义读取错误

问题排查与修复

错误原因

报错Cannot read properties of undefined (reading 'includes')的核心原因是:当React元素没有设置className属性时,child.props.className的值为undefined,直接调用includes方法就会触发这个错误。

修复方案

在判断类名是否包含目标值之前,先确保className存在且为字符串类型,有两种常用写法:

写法1:使用可选链操作符(ES2020+)

可选链?.会在左侧值为undefined或null时停止访问,避免报错:

const newChildren = Children.toArray(children).map((child) => {
  const isItem = isValidElement(child) && child.props.className?.includes('item');

  if (isItem) {
    console.log('is an item, do something with it');
  }

  return child;
});

写法2:兼容旧环境的类型判断

如果项目不支持可选链,可以显式判断className的类型:

const newChildren = Children.toArray(children).map((child) => {
  const isItem = isValidElement(child) && 
                 typeof child.props.className === 'string' && 
                 child.props.className.includes('item');

  if (isItem) {
    console.log('is an item, do something with it');
  }

  return child;
});

补充说明

如果需要精确匹配单个类名(避免类似item-active这种包含item的类名被误判),可以把类名拆分成数组后判断:

const isItem = isValidElement(child) && 
               typeof child.props.className === 'string' && 
               child.props.className.split(/\s+/).includes('item');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:16:11