Tabs tabBarStyle 复用 @theme 变量(NativeWind v5/Tailwind v4)
不要在原生端把 backgroundColor 设成 var(--color-primary)。Tabs 的 tabBarStyle 接收的是 React Native style 对象,不是浏览器 CSS。未解析的 CSS 变量字符串在 iOS/Android 上不可靠。要复用 @theme 颜色,优先在 Tabs 所在组件中通过 NativeWind 的运行时读取 API 取值,再传给 screenOptions;如果当前版本没有可用的读取 API,就用一份颜色 token 源生成 CSS 和 TS,避免两边手写两份色值。
先确认原因
className="bg-accent" 能用,是因为 NativeWind 会把类名编译/转换成 RN style。screenOptions.tabBarStyle 不是 className,React Navigation 会直接把它当普通 RN style 使用,所以这里必须是 #081126、rgba(...) 或 NativeWind 已解析后的颜色值。确保 global.css 已经在根布局导入,例如 import '../global.css';,否则 CSS 变量本身不存在。
方案一:在组件里读取 CSS 变量
如果安装的 NativeWind v5 提供了 useUnstableNativeVariable,可以在 React 组件顶层读取变量,再传给 screenOptions。注意不要在 screenOptions 的回调函数里调用 Hook;那是普通函数调用,不符合 Hooks 规则。这个 API 名字带 unstable,升级前先确认当前版本的导出和行为。
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useUnstableNativeVariable } from 'nativewind';
export default function TabLayout() {
const primary = useUnstableNativeVariable('--color-primary') ?? 'transparent';
const accent = useUnstableNativeVariable('--color-accent');
return (
<Tabs
screenOptions={{
headerShown: false,
tabBarStyle: {
position: 'absolute',
bottom: 25,
left: 20,
right: 20,
elevation: 0,
backgroundColor: primary,
},
}}
>
{tabs.map((tab) => (
<Tabs.Screen
key={tab.name}
name={tab.name}
options={{
tabBarIcon: ({ color }) => (
<Ionicons name={tab.icon} size={32} color={accent ?? color} />
),
}}
/>
))}
</Tabs>
);
}
这里的 ?? 'transparent' 只是变量读取失败时的兜底,不复制设计色值;accent ?? color 还能保留导航器传入的默认颜色作为后备。如果你的版本没有 useUnstableNativeVariable,或者它读不到 global.css 里的 @theme 变量,就不要继续硬猜 API,改用方案二。
方案二:单一颜色源生成 CSS 和 TS
把颜色放在一个 TS/JSON 文件里,再用脚本或构建步骤生成 global.css 的 @theme 块。这样 tabBarStyle 用 TS 常量,className 用 CSS 变量,颜色只维护一次。例如:
// theme.ts
export const colors = {
primary: '#081126',
accent: '#ea7a53',
background: '#fff9e3',
} as const;
backgroundColor: colors.primary,
<Ionicons name={tab.icon} size={32} color={colors.accent} />
global.css 中的 @theme 由同一份 colors 生成即可。不要一边在 @theme 手写 #081126,一边在 TS 里再手写一次;否则后面改色一定会漏。
注意事项
var(--color-primary)在 Web 上可能能工作,但原生端不要依赖。useUnstableNativeVariable是 unstable API,锁版本或写兼容层更稳。- 如果
tabBarIcon需要区分激活/未激活,保留color参数做逻辑,不要无条件覆盖。 - 用方案二时,生成脚本要纳入构建流程,避免
global.css和 TS 不同步。
备注:内容仅供参考。
