NativeWind 4.x 将 Tailwind CSS 3.x 引入 React Native,使 View、Text、Pressable、ScrollView 等 RN 组件支持 className 属性,提供熟悉的 Tailwind 工具类并原生渲染。
用途 用于在 React Native 组件上应用 Tailwind 类、配置 NativeWind,或将 Web 端 Tailwind 写法迁移到 React Native。
安装 pnpm add nativewind tailwindcss@3,并配置 babel 与 metro。
初始设置
- 安装:pnpm add nativewind tailwindcss@3
- 创建 tailwind.config.js,content 路径指向 app/、components/ 等目录
- 创建 global.css,包含 @tailwind base; @tailwind components; @tailwind utilities;
- 更新 babel.config.js:添加 nativewind/babel 预设
- 更新 metro.config.js:使用 withNativeWind 包裹
- 创建 nativewind-env.d.ts,内容为 /// <reference types="nativewind/types" />
- 在根 _layout.tsx 中导入 global.css
为组件添加样式 导入 RN 组件(View、Text、Pressable 等),使用 className 属性传入 Tailwind 工具类;ScrollView/FlashList 的内层样式使用 contentContainerClassName;在设备或模拟器上验证渲染。
配置文件 需要三个配置文件:
- babel.config.js:添加 NativeWind 预设,presets: ['babel-preset-expo', 'nativewind/babel']
- metro.config.js:用 NativeWind 包裹 Metro 配置,withNativeWind(config, { input: './global.css' })
- tailwind.config.js:标准 Tailwind 3.x 配置,包含 RN 内容路径,content: ['./app//*.{ts,tsx}', './components//*.{ts,tsx}']
className 属性 NativeWind 为所有 RN 核心组件增加 className 支持,示例: <View className="flex-1 bg-white p-4"> <Text className="text-lg font-bold text-gray-900"> <Pressable className="bg-blue-500 rounded-lg p-3"> <ScrollView className="flex-1" contentContainerClassName="p-4 gap-3">
与 Web Tailwind 的关键差异
- hover:bg-gray-100:不可用,触屏设备无 hover
- cursor-pointer:不适用,改用 Pressable
- flex:Web 默认 row,RN 默认 column
- 裸字符串:必须用 <Text> 包裹
- div:对应 View,没有 HTML 元素
- gap-4:NativeWind 4.x 支持
- grid:不支持,使用 flex 布局
条件类名
可条件拼接类名字符串,例如 className={px-4 py-2 rounded-lg ${isActive ? 'bg-blue-500' : 'bg-gray-200'}},或使用 clsx/cn 等工具。
ScrollView 样式 ScrollView 有两个 className 目标:className 用于外层容器样式;contentContainerClassName 用于内层内容样式(padding、gap、对齐)。滚动内容的 padding 与间距应始终使用 contentContainerClassName。
主题定制 可通过 tailwind.config.js 的 theme 扩展,例如 theme: { extend: { colors: { brand: { 50: '...', 500: '...', 900: '...' } }, fontFamily: { sans: ['Inter'] } } }
最佳实践
- 创建 nativewind-env.d.ts 以获得 TypeScript 的 className 类型支持
- ScrollView 内层间距使用 contentContainerClassName,而非 className
- RN 中 flex 默认为 column,需要时显式添加 flex-row
- 在根 _layout.tsx 顶部导入 global.css
- 一致使用 Tailwind 间距刻度,避免与 StyleSheet 混用
- 保持 tailwind.config.js 的 content 路径准确,避免样式缺失
- 同级元素间距使用 gap-* 而非 margin
反模式
- 在同一组件混用 StyleSheet.create() 与 className
- 使用 hover: 或 cursor- 工具类(移动端不可用)
- 忘记在 ScrollView 上使用 contentContainerClassName(padding 不会通过 className 生效)
- 使用 grid 工具类(RN 不支持,应使用 flex 布局)
- 不使用 <Text> 包裹裸字符串(在 RN 中会崩溃)
- tailwind.config.js 的 content 数组未包含所有源目录
- 使用 Tailwind CSS 4.x 语法(NativeWind 需要 Tailwind 3.x)