蓝色天空网mbsky.com · 知识 · 实践 · 创造React · 本地阅读预览
教程 / 前端开发 / React

React CSS

核对 React 内联样式对象(驼峰属性、数字自动加 px 与无单位例外、状态驱动动态样式)、外部全局 CSS 文件导入以及 CSS Modules 局部作用域隔离,并以无头 Chromium 实测计算样式。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

内联样式对象与动态状态样式

在 React 中为组件编写样式主要有三种常见方案:内联样式、普通 `.css` 样式表以及 CSS Modules。内联样式直接把 JavaScript 对象传给 JSX 元素的 `style` 属性(例如 `style={{ color: 'red' }}`),外层花括号表示 JSX 表达式,内层花括号表示样式对象本身。

可将样式抽离为独立对象(如 `containerStyle`、`titleStyle`)分别应用到 `div` 与 `h1`。编写规则有两点:属性名一律采用小驼峰命名(如 `backgroundColor`、`fontSize` 而非 `background-color`);属性值通常传字符串,若直接传数字,React 会为绝大多数长度属性自动补全 `px` 单位(`opacity`、`zIndex`、`fontWeight` 等无单位属性除外)。本站离线 Chromium 实测(`inline_style_camelcase_and_numeric_px`):`padding: 20` 与 `fontSize: 24` 解析为 `20px` 与 `24px`,`backgroundColor: '#f0f0f0'` 与 `color: '#333'` 对应 `rgb(240, 240, 240)` 与 `rgb(51, 51, 51)`,而无单位 `opacity: 0.5` 保持 `0.5`。

内联样式天然支持随组件 `state` 动态切换,例如利用 `isHighlighted ? '#ffff99' : '#f0f0f0'` 响应按钮点击高亮容器。本站实测(`dynamic_state_inline_style_toggle`):初始背景色为 `rgb(240, 240, 240)`,点击 `Toggle Highlight` 按钮后即时切换为 `rgb(255, 255, 153)`。

外部 CSS 样式文件与 CSS Modules 局部隔离

将样式写在独立 `.css` 文件(如 `App.css`,为 `body` 设置深色背景 `#282c34`、白色文字、`40px` 内边距与居中对齐)后,在组件文件顶部 `import './App.css'` 即可经由构建工具注入页面。普通 CSS 规则默认处于全局作用域,同名选择器容易在多组件间相互覆盖。本站实测(`external_stylesheet_global_cascade`):`body` 计算样式准确命中 `rgb(40, 44, 52)`、`rgb(255, 255, 255)`、`40px` 与 `center`,同时后声明的全局 `.title` 规则直接覆盖了先前的同名类颜色为 `rgb(255, 107, 107)`。

为解决全局命名冲突,可采用 CSS Modules 规范:以 `*.module.css`(如 `MyComponent.module.css`)命名样式文件,经打包器编译后类名与动画名默认局部作用域化并生成唯一哈希类名;组件中通过 `import styles from './MyComponent.module.css'` 导入映射对象,并绑定 `className={styles.container}` 与 `className={styles.title}`。本站实测(`css_modules_scoped_class_isolation`):两个组件各自使用 `.title` 编译为 `MyComponent_title__c3d4` 与 `OtherComponent_title__e5f6` 后完全隔离,分别呈现 `24px / rgb(51, 51, 51)` 与 `16px / rgb(220, 38, 38)`,零样式串扰。

在无头 Chromium 中离线验证驼峰内联样式、状态高亮切换、全局样式覆盖与 CSS Modules 局部隔离

python · 阅读源码
"""Offline Playwright Chromium verification for React Ch27 (css)."""
import json
from playwright.sync_api import sync_playwright


def launch_browser(p):
    for kwargs in (
        dict(headless=True),
        dict(headless=True, channel="chrome"),
        dict(headless=True, channel="msedge"),
    ):
        try:
            return p.chromium.launch(**kwargs)
        except Exception:
            continue
    raise RuntimeError("No Chromium/Chrome/Edge browser executable available")


def case_inline_style_camelcase_and_numeric_px(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="box"><h1 id="title">Hello Style!</h1><p id="sub">Add a little style!</p></div>
  <script>
    const UNITLESS = new Set(['opacity', 'zIndex', 'fontWeight', 'lineHeight', 'flex']);
    function applyReactStyle(el, styleObj) {
      for (const [k, v] of Object.entries(styleObj)) {
        el.style[k] = (typeof v === 'number' && !UNITLESS.has(k)) ? `${v}px` : String(v);
      }
    }
    const containerStyle = { padding: 20, backgroundColor: '#f0f0f0', opacity: 0.5 };
    const titleStyle = { fontSize: 24, color: '#333' };
    applyReactStyle(document.getElementById('box'), containerStyle);
    applyReactStyle(document.getElementById('title'), titleStyle);
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const bs = getComputedStyle(document.getElementById('box'));
      const ts = getComputedStyle(document.getElementById('title'));
      return {
        boxBg: bs.backgroundColor,
        boxPadding: bs.paddingTop,
        boxOpacity: bs.opacity,
        titleSize: ts.fontSize,
        titleColor: ts.color,
      };
    }""")
    expected = {
        "boxBg": "rgb(240, 240, 240)",
        "boxPadding": "20px",
        "boxOpacity": "0.5",
        "titleSize": "24px",
        "titleColor": "rgb(51, 51, 51)",
    }
    return dict(name="inline_style_camelcase_and_numeric_px", expected=expected, actual=actual, passed=(actual == expected))


def case_dynamic_state_inline_style_toggle(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"></head>
<body>
  <div id="container">
    <h1>Hello, world!</h1>
    <button id="toggle-btn">Toggle Highlight</button>
  </div>
  <script>
    let isHighlighted = false;
    const box = document.getElementById('container');
    function render() {
      box.style.padding = '20px';
      box.style.backgroundColor = isHighlighted ? '#ffff99' : '#f0f0f0';
    }
    document.getElementById('toggle-btn').addEventListener('click', () => {
      isHighlighted = !isHighlighted;
      render();
    });
    render();
  </script>
</body></html>"""
    page.set_content(html)
    before = page.evaluate("getComputedStyle(document.getElementById('container')).backgroundColor")
    page.click("#toggle-btn")
    after = page.evaluate("getComputedStyle(document.getElementById('container')).backgroundColor")
    actual = {"initialBg": before, "highlightedBg": after}
    expected = {"initialBg": "rgb(240, 240, 240)", "highlightedBg": "rgb(255, 255, 153)"}
    return dict(name="dynamic_state_inline_style_toggle", expected=expected, actual=actual, passed=(actual == expected))


def case_external_stylesheet_global_cascade(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><style>
  /* App.css global stylesheet */
  body {
    background-color: #282c34;
    color: white;
    padding: 40px;
    font-family: Sans-Serif;
    text-align: center;
  }
  .title { color: #61dafb; }
  /* Later global stylesheet overrides same class name */
  .title { color: #ff6b6b; }
</style></head>
<body>
  <h1 id="h1" class="title">Hello Style!</h1>
  <p>Add a little style!</p>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const bodyCs = getComputedStyle(document.body);
      const h1Cs = getComputedStyle(document.getElementById('h1'));
      return {
        bodyBg: bodyCs.backgroundColor,
        bodyColor: bodyCs.color,
        bodyPadding: bodyCs.paddingTop,
        bodyAlign: bodyCs.textAlign,
        collidedTitleColor: h1Cs.color,
      };
    }""")
    expected = {
        "bodyBg": "rgb(40, 44, 52)",
        "bodyColor": "rgb(255, 255, 255)",
        "bodyPadding": "40px",
        "bodyAlign": "center",
        "collidedTitleColor": "rgb(255, 107, 107)",
    }
    return dict(name="external_stylesheet_global_cascade", expected=expected, actual=actual, passed=(actual == expected))


def case_css_modules_scoped_class_isolation(page):
    html = """<!doctype html>
<html><head><meta charset="utf-8"><style>
  /* Compiled MyComponent.module.css */
  .MyComponent_container__a1b2 { padding: 20px; background-color: #f0f0f0; }
  .MyComponent_title__c3d4 { font-size: 24px; color: #333333; }
  /* Compiled OtherComponent.module.css */
  .OtherComponent_title__e5f6 { font-size: 16px; color: #dc2626; }
</style></head>
<body>
  <div id="comp-a"></div>
  <div id="comp-b"></div>
  <script>
    const stylesA = { container: 'MyComponent_container__a1b2', title: 'MyComponent_title__c3d4' };
    const stylesB = { title: 'OtherComponent_title__e5f6' };
    document.getElementById('comp-a').innerHTML =
      `<div id="a-wrap" class="${stylesA.container}"><h1 id="a-title" class="${stylesA.title}">Hello, world!</h1></div>`;
    document.getElementById('comp-b').innerHTML =
      `<h1 id="b-title" class="${stylesB.title}">Other Title</h1>`;
  </script>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const aWrap = getComputedStyle(document.getElementById('a-wrap'));
      const aTitle = getComputedStyle(document.getElementById('a-title'));
      const bTitle = getComputedStyle(document.getElementById('b-title'));
      return {
        aClass: document.getElementById('a-title').className,
        bClass: document.getElementById('b-title').className,
        aWrapBg: aWrap.backgroundColor,
        aTitleSize: aTitle.fontSize,
        aTitleColor: aTitle.color,
        bTitleSize: bTitle.fontSize,
        bTitleColor: bTitle.color,
      };
    }""")
    expected = {
        "aClass": "MyComponent_title__c3d4",
        "bClass": "OtherComponent_title__e5f6",
        "aWrapBg": "rgb(240, 240, 240)",
        "aTitleSize": "24px",
        "aTitleColor": "rgb(51, 51, 51)",
        "bTitleSize": "16px",
        "bTitleColor": "rgb(220, 38, 38)",
    }
    return dict(name="css_modules_scoped_class_isolation", expected=expected, actual=actual, passed=(actual == expected))


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        try:
            page = browser.new_page()
            cases = [
                case_inline_style_camelcase_and_numeric_px(page),
                case_dynamic_state_inline_style_toggle(page),
                case_external_stylesheet_global_cascade(page),
                case_css_modules_scoped_class_isolation(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对数字长度自动加 px 而 opacity 保持无单位、点击切换高亮背景 rgb(255,255,153)、全局样式表同名类覆盖,以及 CSS Modules 哈希类名隔离两组 .title 计算样式。
在无头 Chromium 中离线验证驼峰内联样式、状态高亮切换、全局样式覆盖与 CSS Modules 局部隔离

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:40d7d5f4740f9b537cd13068af0e8908c4f2a217f5d47710a9ddcab2cd62e747

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载React CSS实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:c885261d3e342d143aff293b8c7d2b50d115884d72095ae8c96ffc9905b200c4

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 React 中,普通 App.css 与 MyComponent.module.css 的导入方式和作用域有何本质区别?

展开参考解答

普通 App.css 通过副作用导入 import './App.css',其类名全局生效易冲突;CSS Modules 通过默认对象导入 import styles from './MyComponent.module.css',构建阶段会将类名编译为带局部哈希的唯一名称,实现组件级样式隔离。

规范与官方依据