在 React Native(RN)中,StyleSheet.create() 和内联样式(inline style)都可以定义样式,但官方更推荐使用 StyleSheet.create() 来管理大部分样式。
StyleSheet.create() 的好处
1. 更好的代码组织
样式与 JSX 分离,可读性更高。
javascript
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
title: {
fontSize: 18,
fontWeight: 'bold',
},
});
return (
<View style={styles.container}>
<Text style={styles.title}>Hello</Text>
</View>
);
相比:
css
<View
style={{
flex: 1,
backgroundColor: '#fff',
}}
>
组件不会充满大量样式对象,更容易维护。
2. 类型检查(TypeScript 支持更好)
StyleSheet.create() 会进行类型校验。
例如:
arduino
const styles = StyleSheet.create({
text: {
fontSze: 18, // ❌ 拼写错误,TS 会报错
},
});
如果写成内联:
ini
<Text style={{ fontSze: 18 }} />
很多情况下错误不能及时发现(取决于类型推断)。
3. 避免重复创建对象
例如:
css
<Text style={{ color: 'red' }} />
每次组件重新渲染:
css
{ color: 'red' }
都会创建一个新的对象。
而
css
const styles = StyleSheet.create({
text: {
color: 'red',
},
});
styles.text 是同一个引用:
arduino
styles.text === styles.text // true
对于依赖浅比较(如 React.memo)的组件,这可以减少不必要的更新。
4. 更容易复用
ini
<Text style={styles.title} />
<Text style={styles.title} />
<Text style={styles.title} />
而不是:
ini
<Text style={{ fontSize: 18, color: 'blue' }} />
<Text style={{ fontSize: 18, color: 'blue' }} />
<Text style={{ fontSize: 18, color: 'blue' }} />
修改时只需改一个地方。
5. IDE 支持更好
- 自动补全
- 跳转定义
- 重构
- 查找引用
这些在大型项目中非常有帮助。
内联样式的弊端
1. 每次 render 都创建新对象
css
<View style={{ flex: 1 }} />
每次 render:
yaml
{} !== {}
React 认为引用发生变化。
例如:
javascript
const Child = React.memo(({ style }) => {
console.log('render');
return <View style={style} />;
});
<Child style={{ flex: 1 }} />
父组件每次更新时:
yaml
style !== style
Child 可能仍会重新渲染。
如果改成:
ini
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
<Child style={styles.container} />
引用保持稳定,更有利于性能优化。
2. JSX 可读性下降
例如:
less
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
paddingHorizontal: 20,
borderRadius: 10,
marginTop: 15,
}}
>
大量样式会淹没组件结构。
3. 难以维护
如果多个地方:
css
{
color: '#333',
fontSize: 16,
}
以后改颜色,需要一个个修改。
4. 不方便统一主题
例如:
css
style={{ color: theme.text }}
散落在很多组件中。
使用 StyleSheet.create() 配合主题对象或动态样式函数,更容易集中管理。
那是不是不能用内联样式?
不是。
适合使用内联样式的场景:
动态值
例如:
css
<Text
style={{
color: isDark ? '#fff' : '#000',
}}
/>
或者:
css
<View
style={{
width: progress + '%',
}}
/>
更推荐的写法是结合 StyleSheet:
ini
<View
style={[
styles.container,
isDark && styles.dark,
{
width: progress + '%',
},
]}
/>
其中:
- 静态样式 放在
StyleSheet.create() - 动态样式使用内联对象或条件样式覆盖
StyleSheet.create() 还有性能优势吗?
早期 React Native 文档曾提到 StyleSheet.create() 有一定性能优化(例如将样式注册为内部 ID)。随着 React Native 新架构(Fabric)和引擎的发展,它带来的运行时性能优势已经不像早期那样明显。
目前使用 StyleSheet.create() 的主要价值在于:
- 保持样式对象引用稳定,减少因新对象导致的无谓更新。
- 获得更好的类型检查、IDE 支持和代码组织能力。
- 提高样式复用性和可维护性。
因此,在现代 React Native 项目中的最佳实践通常是:
- 绝大多数静态样式 使用
StyleSheet.create()。 - 少量依赖运行时数据的动态样式 使用内联样式,或通过
style={[styles.base, dynamicStyle]}的方式组合。这样既兼顾了代码质量,也满足了动态样式的需求。