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

React/Bootstrap中添加style=""导致页面空白问题求助

问题描述

我用React结合Bootstrap写了以下组件代码:

import React from "react";
import 'bootstrap/dist/css/bootstrap.css';
const Downloads = () => {
  return (
    <div class="text-bg-secondary text-white p-2">
        <div class="card">
  <div class="card-body">
    <h5 class="card-title">Card title</h5>
    <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="card-link">Card link</a>
    <a href="#" class="card-link">Another link</a>
  </div>
</div>
    </div>
  );
};
  
export default Downloads;

这段代码在不添加style属性时能正常运行,但只要给任意元素加style=""(比如<div style="">),页面就变成空白。我已经试过重新安装Bootstrap,还是没解决,希望能修复这个问题。

解决方法

出现这个问题的核心原因是React中使用DOM属性的规则和原生HTML不同,具体需要修正两点:

  1. 替换class为className
    React不支持原生HTML的class属性,必须用className指定CSS类名。原代码中的class写法本身存在潜在渲染隐患,添加style后会触发错误导致页面空白。

  2. style属性需传入对象而非字符串
    React的style属性要求接收JavaScript对象,而非原生HTML的字符串格式。空字符串style=""属于语法错误,会直接引发页面崩溃。

  • 空样式写法:style={{}}
  • 带样式写法:style={{ color: 'red', padding: '10px' }}

完整修正后的代码

import React from "react";
import 'bootstrap/dist/css/bootstrap.css';
const Downloads = () => {
  return (
    <div className="text-bg-secondary text-white p-2" style={{}}>
        <div className="card">
          <div className="card-body">
            <h5 className="card-title">Card title</h5>
            <h6 className="card-subtitle mb-2 text-muted">Card subtitle</h6>
            <p className="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
            <a href="#" className="card-link">Card link</a>
            <a href="#" className="card-link">Another link</a>
          </div>
        </div>
    </div>
  );
};
  
export default Downloads;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 01:10:15