蓝色天空.知识 · 实践 · 创造
我的收藏
React 教程目录 42章
React / LEARN BY DOING

React Tailwind CSS

核对 Tailwind CSS 实用工具优先理念、React 项目安装配置(含 PostCSS、content 扫描清理与 @tailwind 指令)、JSX 类名组合实践及静态扫描约束,并以无头 Chromium 实测布局与悬停态。

学完这一章,你能够

  • 核对 Tailwind CSS 实用工具优先理念、React 项目安装配置(含 PostCSS、content 扫描清理与 @tailwind 指令)、JSX 类名组合实践及静态扫描约束,并以无头 Chromium 实测布局与悬停态。

Tailwind CSS 实用工具优先理念与官方入口

Tailwind CSS 是一套实用工具优先(Utility-First)的 CSS 框架:不同于传统预制整套按钮/卡片语义类的组件库,它提供细粒度原子类(如间距、Flex 对齐、颜色与圆角),可直接组合写在 React JSX 的 `className` 属性中,使样式结构紧凑且易于模块化复用。延伸学习可查阅本站 Tailwind CSS 专题及下方收录的 Tailwind CSS 官网与 GitHub 开源仓库。

在 React 项目中安装、配置 content 与引入基础指令

传统接入流程可从新建 React 项目起步(早期示例使用 `npx create-react-app my-app` 创建项目,注意进入目录应与创建名一致即 `cd my-app`;现代新项目更推荐采用 Vite `npm create vite@latest`)。随后在项目根目录安装 `tailwindcss`、`postcss` 与 `autoprefixer` 开发依赖并运行 `npx tailwindcss init -p`,自动生成 `tailwind.config.js` 与 `postcss.config.js`,形成包含 `src/App.js`、`src/index.css`、`src/index.js` 与配置文件的标准目录结构。

在 Tailwind v3 配置中,需编辑 `tailwind.config.js` 的 `content` 数组为 `["./src/**/*.{js,jsx,ts,tsx}"]`,使构建期扫描源码并仅保留实际用到的工具类以瘦身 CSS 产物;接着在 `src/index.css` 写入 `@tailwind base;`、`@tailwind components;` 与 `@tailwind utilities;` 三条指令(若升级至 Tailwind v4,则进一步简化为 CSS-first 单行 `@import "tailwindcss";`)。本站离线实测静态类扫描模型(`tailwind_content_scan_tree_shaking_model`):在 18 个候选工具类中,静态分析精准保留 13 个已用类并裁剪 5 个未用类,同时验证了模板字符串动态拼接 ``bg-${color}-500`` 无法被静态扫描识别(`dynamicBgRedDetected === false`),工程上应写出完整静态类名映射。

在 React JSX 中使用工具类与悬停/状态切换实测

完成配置后,在 `src/index.js` 导入 `./index.css` 并将 `<App />` 挂载到 `#root`(包裹于 `<React.StrictMode>`),即可在 `App.js` 中用 `min-h-screen bg-gray-100 flex items-center justify-center` 搭出全屏居中画布,内嵌 `bg-white p-8 rounded-lg shadow-lg` 卡片、标题(`text-2xl font-bold text-gray-900`)、正文(`mt-4 text-gray-600`)及带悬停变色的按钮(`mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700`)。

本地启动开发服务(`npm start` 或 Vite `npm run dev`)访问本地端口即可实时预览效果(来源页面附带 1 张卡片效果图,因含第三方站标字样仅留存私有像素核查证据)。本站离线无头 Chromium 实测(`tailwind_card_utility_layout_and_typography`、`tailwind_hover_state_and_dynamic_classname`):外层容器准确呈现 `flex` 双向居中与浅灰背景 `rgb(243, 244, 246)`,卡片内边距 `32px`、圆角 `8px`,标题字号 `24px` 字重 `700`;按钮常态背景 `rgb(59, 130, 246)`,鼠标悬停即切换为 `hover:bg-blue-700` 对应的 `rgb(29, 78, 216)`,点击触发 React 状态类名切换后变为 `rgb(5, 150, 105)`。

在无头 Chromium 中离线验证 Tailwind 卡片布局排版、hover 悬停变色、状态类名切换与 content 静态扫描模型

含完整源码 · 184 行
展开查看收起
python
"""Offline Playwright Chromium verification for React Ch29 (tailwind)."""
import json
import re
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")


TAILWIND_UTILITY_CSS = """
*, ::before, ::after { box-sizing: border-box; border: 0 solid #e5e7eb; }
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; }
.min-h-screen { min-height: 100vh; }
.bg-gray-100 { background-color: rgb(243, 244, 246); }
.bg-white { background-color: rgb(255, 255, 255); }
.bg-blue-500 { background-color: rgb(59, 130, 246); }
.bg-emerald-600 { background-color: rgb(5, 150, 105); }
.hover\\:bg-blue-700:hover { background-color: rgb(29, 78, 216); }
.flex { display: flex; }
.items-center { align-items: center; }
.justify-center { justify-content: center; }
.p-8 { padding: 32px; }
.py-2 { padding-top: 8px; padding-bottom: 8px; }
.px-4 { padding-left: 16px; padding-right: 16px; }
.mt-4 { margin-top: 16px; }
.mt-6 { margin-top: 24px; }
.rounded { border-radius: 4px; }
.rounded-lg { border-radius: 8px; }
.shadow-lg { box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1); }
.text-2xl { font-size: 24px; line-height: 32px; }
.font-bold { font-weight: 700; }
.text-gray-900 { color: rgb(17, 24, 39); }
.text-gray-600 { color: rgb(75, 85, 99); }
.text-white { color: rgb(255, 255, 255); }
"""


def case_tailwind_card_utility_layout_and_typography(page):
    html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TAILWIND_UTILITY_CSS}</style></head>
<body>
  <div id="shell" class="min-h-screen bg-gray-100 flex items-center justify-center">
    <div id="card" class="bg-white p-8 rounded-lg shadow-lg">
      <h1 id="title" class="text-2xl font-bold text-gray-900">Hello, React + Tailwind!</h1>
      <p id="desc" class="mt-4 text-gray-600">实用工具优先样式在 JSX className 中直接组合。</p>
      <button id="cta" class="mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700">点我试试</button>
    </div>
  </div>
</body></html>"""
    page.set_content(html)
    actual = page.evaluate("""() => {
      const shell = getComputedStyle(document.getElementById('shell'));
      const card = getComputedStyle(document.getElementById('card'));
      const title = getComputedStyle(document.getElementById('title'));
      const btn = getComputedStyle(document.getElementById('cta'));
      return {
        shellDisplay: shell.display,
        shellAlign: shell.alignItems,
        shellJustify: shell.justifyContent,
        shellBg: shell.backgroundColor,
        cardPadding: card.paddingTop,
        cardRadius: card.borderTopLeftRadius,
        titleSize: title.fontSize,
        titleWeight: title.fontWeight,
        btnBg: btn.backgroundColor,
        btnPadY: btn.paddingTop,
        btnPadX: btn.paddingLeft,
      };
    }""")
    expected = {
        "shellDisplay": "flex",
        "shellAlign": "center",
        "shellJustify": "center",
        "shellBg": "rgb(243, 244, 246)",
        "cardPadding": "32px",
        "cardRadius": "8px",
        "titleSize": "24px",
        "titleWeight": "700",
        "btnBg": "rgb(59, 130, 246)",
        "btnPadY": "8px",
        "btnPadX": "16px",
    }
    return dict(name="tailwind_card_utility_layout_and_typography", expected=expected, actual=actual, passed=(actual == expected))


def case_tailwind_hover_state_and_dynamic_classname(page):
    html = f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TAILWIND_UTILITY_CSS}</style></head>
<body>
  <div id="root"></div>
  <script>
    let active = false;
    function render() {{
      const cls = active
        ? 'mt-6 bg-emerald-600 text-white py-2 px-4 rounded'
        : 'mt-6 bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-700';
      document.getElementById('root').innerHTML = `<button id="cta" class="${{cls}}">点我试试</button>`;
      document.getElementById('cta').addEventListener('click', () => {{
        active = !active;
        render();
      }});
    }}
    render();
  </script>
</body></html>"""
    page.set_content(html)
    normal_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
    page.hover("#cta")
    hover_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
    page.click("#cta")
    clicked_bg = page.evaluate("getComputedStyle(document.getElementById('cta')).backgroundColor")
    actual = {"normalBg": normal_bg, "hoverBg": hover_bg, "clickedBg": clicked_bg}
    expected = {
        "normalBg": "rgb(59, 130, 246)",
        "hoverBg": "rgb(29, 78, 216)",
        "clickedBg": "rgb(5, 150, 105)",
    }
    return dict(name="tailwind_hover_state_and_dynamic_classname", expected=expected, actual=actual, passed=(actual == expected))


def case_tailwind_content_scan_tree_shaking_model(page):
    jsx_source = """
    const App = () => (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="bg-white p-8 rounded-lg shadow-lg">
          <h1 className="text-2xl font-bold text-gray-900">Title</h1>
          <button className={`bg-${color}-500 text-white`}>Go</button>
        </div>
      </div>
    );
    """
    catalog = [
        "min-h-screen", "bg-gray-100", "flex", "items-center", "justify-center",
        "bg-white", "p-8", "rounded-lg", "shadow-lg", "text-2xl", "font-bold",
        "text-gray-900", "text-white", "bg-red-500", "bg-purple-500", "p-2", "mt-10", "hidden"
    ]
    tokens = set(re.findall(r"[a-zA-Z0-9_:/-]+", jsx_source))
    kept = [c for c in catalog if c in tokens]
    pruned = [c for c in catalog if c not in tokens]
    actual = {
        "catalogCount": len(catalog),
        "keptCount": len(kept),
        "prunedCount": len(pruned),
        "dynamicBgRedDetected": "bg-red-500" in kept,
        "textWhiteDetected": "text-white" in kept,
    }
    expected = {
        "catalogCount": 18,
        "keptCount": 13,
        "prunedCount": 5,
        "dynamicBgRedDetected": False,
        "textWhiteDetected": True,
    }
    return dict(name="tailwind_content_scan_tree_shaking_model", 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_tailwind_card_utility_layout_and_typography(page),
                case_tailwind_hover_state_and_dynamic_classname(page),
                case_tailwind_content_scan_tree_shaking_model(page),
            ]
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 Flex 居中卡片与标题字号/字重/内边距计算样式、hover:bg-blue-700 悬停态与点击切换 emerald 态,以及静态扫描裁剪 5 个未用类且漏检动态拼接类名。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a3190.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3190.zip

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Tailwind 在构建期通过正则静态扫描 content 配置路径中的完整类名字符串来按需生成 CSS,不会执行运行时 JS 拼接逻辑;动态拼出的类名若未以完整字面量出现,将不会被生成进最终样式表。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习