StyleSheet.create 是强制入口,React Native 原生层仅识别整数 ID 样式,不支持字符串/对象样式;必须顶层调用、全驼峰命名、省略单位、限定颜色格式,且不支持嵌套、伪类、媒体查询;styled-components 需额外配置 babel 插件并使用 /native 入口,动态样式与主题机制与 StyleSheet 互斥。

StyleSheet.create 是强制入口,不是可选项
React Native 的原生渲染层(iOS 的 RCTView、Android 的 ReactRootView)只认整数 ID 样式,不解析字符串或对象。绕过 StyleSheet.create 直接传 { fontSize: 16 } 可能临时跑通,但会触发 StyleSheet: Invalid style 警告,热重载失败,Hermes 引擎下直接报错拒绝渲染。
必须在模块顶层调用,不能放在函数或条件分支里:
const styles = StyleSheet.create({
container: { padding: 16, backgroundColor: '#fff' },
title: { fontSize: 18, fontWeight: '600' }
});
- 属性名全驼峰:
backgroundColor✅,background-color❌ - 单位省略:
padding: 16✅,padding: 16px❌(不支持px、vh、vw) - 颜色值仅支持十六进制、
rgb()、rgba(),不支持red或hsl() - 不支持嵌套、伪类(
:hover)、媒体查询、@import
Styled Components 需要额外配置才能生效
直接 yarn add styled-components 后 import 并使用,大概率会白屏或报 Invalid hook call —— 因为 React Native 版本的 styled-components 必须搭配 babel-plugin-styled-components 和正确 Babel 配置。
关键三步缺一不可:
立即学习“前端免费学习笔记(深入)”;
- 安装:
yarn add styled-components+yarn add -D @types/styled-components babel-plugin-styled-components - 修改
babel.config.js,在plugins中加入:['babel-plugin-styled-components', { displayName: true }] - 导入时必须用
styled-components/native,不是styled-components:import styled from 'styled-components/native';
否则组件会渲染为空,DevTools 里看不到样式节点,也无警告提示——这是最常被忽略的兼容断点。
动态样式写法差异极大,别混用逻辑
StyleSheet.create 不接受运行时变量或表达式,所有条件必须提至组件内合并;styled-components 则天然支持基于 props 的插值函数,写法和语义完全不同。
比如实现“按钮根据 variant 变色”:
// ❌ StyleSheet 写法(冗长且易错)
const styles = StyleSheet.create({
btnPrimary: { backgroundColor: '#007AFF' },
btnSecondary: { backgroundColor: '#5856D6' }
});
// 使用时要手动合并:
style={[styles.btnPrimary, props.variant === 'secondary' && styles.btnSecondary]}
// ✅ styled-components 写法(简洁直观)
const Button = styled.TouchableOpacity<{variant: 'primary' | 'secondary'}>`
background-color: ${props => props.variant === 'primary' ? '#007AFF' : '#5856D6'};
`;
-
StyleSheet动态逻辑靠数组合并 + 三元判断,容易漏掉false值导致样式丢失 -
styled-components插值函数返回字符串,空值自动忽略,类型安全靠 TypeScript 推断 - 不要在
styled.xxx模板中写if/else,只用三元或箭头函数返回 CSS 字符串
主题与复用机制完全不在一个抽象层级
StyleSheet 本身无主题概念,你要自己管理颜色/尺寸常量对象,再靠 JS 合并;styled-components 的 ThemeProvider 是运行时注入,支持深色模式切换、动态字体缩放等原生难以覆盖的场景。
例如深色模式适配:
// StyleSheet 方式(需手动监听、重渲染、重计算所有样式)
const theme = useColorScheme() === 'dark' ? darkColors : lightColors;
const styles = StyleSheet.create({
text: { color: theme.text }
});
// styled-components 方式(一次注入,全局响应)
const theme = { colors: { text: isDark ? '#fff' : '#000' } };
<ThemeProvider theme={theme}>
<Title />
</ThemeProvider>
const Title = styled.Text`color: ${props => props.theme.colors.text};`;
真正复杂的地方在于:两种方案无法混用。选 StyleSheet 就得承担手动维护主题映射的负担;选 styled-components 就必须接受它对 Babel 和打包体积的侵入——没有“轻量又强大”的中间态。

















