Skip to content

React Native - 样式

在 React Native 中,样式(Styling)是使用 JavaScript 来实现的。你无需直接编写 CSS。相反,你需要创建模仿 CSS 属性的 JavaScript 对象。React Native 使用高度优化的 Flexbox 实现来进行布局。

虽然你可以通过将 JavaScript 对象直接传递给 style 属性(prop)来使用内联样式,但为了更好的组织结构和性能,推荐使用 StyleSheet.create。

StyleSheet.create 允许你在一个地方定义多个样式。它还有助于仅将样式一次性发送到原生端,可能提高性能,并提供对样式属性的验证。

样式属性名通常使用 camelCase(驼峰命名法),例如 backgroundColor 而非 background-color。通常不使用 px 等单位;数字通常代表密度无关像素(density-independent pixels)。

组件示例:

App.js

<html>
<body>
<p>
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const App = () => {
const myName = 'React Native Developer';
return (
&lt;View style={styles.container}&gt;
&lt;Text style={styles.greetingText}&gt;
Hello, {myName}!
&lt;/Text&gt;
&lt;Text style={styles.descriptionText}&gt;
Welcome to learning styling in React Native.
&lt;/Text&gt;
&lt;/View&gt;
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f0f0f0',
padding: 20,
},\n greetingText: {
fontSize: 24,
fontWeight: 'bold',
color: 'dodgerblue',
marginBottom: 10, // Margin between text elements
textAlign: 'center',
},
descriptionText: {
fontSize: 16,
color: 'dimgray',
textAlign: 'center',
},
});
export default App;
</p>
</body>
</html>

输出:此应用程序将显示一条粗体、道奇蓝色的问候消息,其下方是一条暗灰色的描述性消息。这两段文本都将居中显示在一个填充屏幕的浅灰色容器中。

有时,你可能需要为 iOS 和 Android 应用不同的样式。React Native 为此提供了 Platform 模块:

<html>
<body>
<p>
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
textStyle: {
color: Platform.OS === 'ios' ? 'green' : 'blue',
fontSize: Platform.select({
ios: 20,
android: 18,
default: 16, // for other platforms like web
}),
},
});
</p>
</body>
</html>

有关样式的更全面信息,包括不同组件的所有可用样式属性(style props)列表,请参考官方 React Native 文档:样式、文本样式属性 和 视图样式属性。