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

React中创建类Bootstrap ListGroup组件报错:ListGroup.Item未定义

解决ListGroup.Item undefined的问题

你遇到的核心问题是没有把Item组件挂载到ListGroup类本身,而是错误地定义成了类的实例属性,导致外部访问ListGroup.Item时找不到这个属性。

常见错误写法(问题所在)

如果你的代码是类似这样的,就会出现undefined:

class ListGroup extends React.Component {
  // 错误:这是实例属性,只有创建ListGroup实例后才存在
  Item = (props) => {
    return <div className="list-group-item">{props.children}</div>;
  };

  render() {
    return <div className="list-group">{this.props.children}</div>;
  }
}

export default ListGroup;

ListGroup.Item是访问类的静态属性,但上面的写法把Item定义成了实例属性,只有当<ListGroup>被渲染(实例化)后才存在,外部直接访问类的属性自然找不到。

正确的两种实现方式

方式1:类外部挂载Item

这种方式兼容性最好,不需要额外的babel配置:

import React from 'react';

class ListGroup extends React.Component {
  render() {
    return <div className="list-group">{this.props.children}</div>;
  }
}

// 把Item组件直接挂载到ListGroup类上
ListGroup.Item = function ListGroupItem(props) {
  return <div className="list-group-item">{props.children}</div>;
};

export default ListGroup;

方式2:类内部定义静态属性

如果你的项目支持class fields语法(比如用Create React App或配置了babel-plugin-proposal-class-properties),可以直接在类里用static定义:

import React from 'react';

class ListGroup extends React.Component {
  // 用static定义类的静态属性
  static Item = (props) => {
    return <div className="list-group-item">{props.children}</div>;
  };

  render() {
    return <div className="list-group">{this.props.children}</div>;
  }
}

export default ListGroup;

验证使用

现在在其他文件导入后就能正常使用了:

import ListGroup from './ListGroup';

function App() {
  return (
    <ListGroup>
      <ListGroup.Item>列表项1</ListGroup.Item>
      <ListGroup.Item>列表项2</ListGroup.Item>
    </ListGroup>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 17:38:17