StyleSheet
参考文档
StyleSheet 提供了一种类似 CSS 样式表的抽象。
创建一个样式表:
const styles = StyleSheet.create({
container: {
borderRadius: 4,
borderWidth: 0.5,
borderColor: '#d6d7da',
},
title: {
fontSize: 19,
fontWeight: 'bold',
},
activeTitle: {
color: 'red',
},
});
使用一个样式表:
<View style={styles.container}>
<Text style={[styles.title, this.props.isActive && styles.activeTitle]} />
</View>
从代码质量角度:
- 从 render 函数中移除具体的样式内容,可以使代码更清晰易懂。
- 给样式命名也可以对 render 函数中的组件增加语义化的描述。
方法
setStyleAttributePreprocessor()
static setStyleAttributePreprocessor(property, process)
设置用于预处理样式属性值的函数。
create()
static create(obj)
从给定的对象创建一个StyleSheet样式参考。
flatten
static flatten(style)
将一组样式对象融合为一个聚合的样式对象。 或者,可以使用此方法查找由StyleSheet.register返回的ID。
示例:
const styles = StyleSheet.create({
listItem: {
flex: 1,
fontSize: 16,
color: 'white',
},
selectedListItem: {
color: 'green',
},
});
StyleSheet.flatten([styles.listItem, styles.selectedListItem]);
// 返回值为 { flex: 1, fontSize: 16, color: 'green' }
替代写法
const styles = StyleSheet.create({
listItem: {
flex: 1,
fontSize: 16,
color: 'white',
},
selectedListItem: {
color: 'green',
},
});
StyleSheet.flatten(styles.listItem);
// 返回值为 { flex: 1, fontSize: 16, color: 'white' }
// 如果直接打印 styles.listItem,则返回值是一个整数型的ID
此方法在内部使用StyleSheetRegistry.getStyleByID(style)解析由ID表示的样式对象。 因此,一组样式对象(StyleSheet.create()的实例)被分别解析为它们各自的对象,合并为一个对象然后返回。 这也解释了替代用法。
常量
hairlineWidth
const styles = StyleSheet.create({
separator: {
borderBottomColor: '#bbb',
borderBottomWidth: StyleSheet.hairlineWidth,
},
});
这一常量始终是一个整数的像素值(线看起来会像头发丝一样细),并会尽量符合当前平台最细的线的标准。可以用作边框或是两个元素间的分隔线。然而,你不能把它“视为一个常量”,因为不同的平台和不同的屏幕像素密度会导致不同的结果。
如果模拟器缩放过,可能会看不到这么细的线。
absoluteFill
一个非常常见的模式是创建绝对位置和零位置的覆盖图,因此absoluteFill可以方便使用并减少这些重复样式的重复。
absoluteFillObject
有时您可能需要absoluteFill但需要进行一些调整-absoluteFillObject可用于在StyleSheet中创建自定义条目,例如:
const styles = StyleSheet.create({
wrapper: {
...StyleSheet.absoluteFill,
top: 10,
backgroundColor: 'transparent',
},
});