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

Bootstrap样式不生效,badge组件在React的.jsx文件中无法显示怎么办

问题原因

当前安装的Bootstrap版本和教程使用的版本不兼容,MOSH的React教程使用的是Bootstrap 4,而你安装的是Bootstrap 5,两个版本的badge组件类名规则完全不同,旧的badge-primary类在Bootstrap 5中已经废弃,所以样式不生效。

解决方法

  • 方案一:适配Bootstrap 5的类名规则
    修改counter.jsx中span标签的className属性,将原代码的badge badge-primary替换为badge text-bg-primary即可正常显示样式。
    调整后的完整counter.jsx代码如下:
import React, { Component } from "react";

class Counter extends Component {
state = {
    count: 0,
};

render() {
    return (
        <div>
            <span className="badge text-bg-primary">{this.formatCount()}</span>
            <button className="btn btn-secondary ms-2">Increment</button>
        </div>
    );
}

formatCount(){
  const {count} = this.state;
  return count === 0 ? 'Zero' : count;
}
}

export default Counter;

同时可以将index.js中的Bootstrap导入路径简化为import 'bootstrap/dist/css/bootstrap.min.css',React脚手架会自动从node_modules目录中检索对应依赖,无需写相对路径。

  • 方案二:降级到Bootstrap 4版本
    如果希望完全沿用教程中的代码写法,可运行命令npm install bootstrap@4.6.2安装指定的Bootstrap 4版本,安装完成后原有代码无需修改即可正常生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:06:03