StyleSheet

StyleSheet提供了一种类似CSS样式表的抽象。

创建一个样式表:

var 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函数中的原始组件的作用的一种标记。

从性能角度:

  • 创建一个样式表,就可以使得我们后续更容易通过ID来引用样式,而不是每次都创建一个新的对象。
  • 它还使得样式只会在JavaScript和原生之间传递一次,随后的过程都可以只传递一个ID(这个优化还未实现)。

方法#

static create(obj: {[key: string]: any}) #

属性#

hairlineWidth: CallExpression #

这一常量定义了当前平台上的最细的宽度。可以用作边框或是两个元素间的分隔线。例如:

{ borderBottomColor: '#bbb', borderBottomWidth: StyleSheet.hairlineWidth }

这一常量始终是一个整数的像素值(线看起来会像头发丝一样细),并会尽量符合当前平台最细的线的标准。然而,你不能把它“视为一个常量”,因为不同的平台和不同的屏幕像素密度会导致不同的结果。

absoluteFill: CallExpression #

A very common pattern is to create overlays with position absolute and zero positioning, so absoluteFill can be used for convenience and to reduce duplication of these repeated styles.

absoluteFillObject: ObjectExpression #

Sometimes you may want absoluteFill but with a couple tweaks - absoluteFillObject can be used to create a customized entry in a StyleSheet, e.g.:

const styles = StyleSheet.create({ wrapper: { ...StyleSheet.absoluteFillObject, top: 10, backgroundColor: 'transparent', }, });

flatten: CallExpression #

Flattens an array of style objects, into one aggregated style object. Alternatively, this method can be used to lookup IDs, returned by StyleSheet.register.

NOTE: Exercise caution as abusing this can tax you in terms of optimizations.

IDs enable optimizations through the bridge and memory in general. Refering to style objects directly will deprive you of these optimizations.

Example:

var styles = StyleSheet.create({ listItem: { flex: 1, fontSize: 16, color: 'white' }, selectedListItem: { color: 'green' } }); StyleSheet.flatten([styles.listItem, styles.selectedListItem]) // returns { flex: 1, fontSize: 16, color: 'green' }

Alternative use:

StyleSheet.flatten(styles.listItem); // return { flex: 1, fontSize: 16, color: 'white' } // Simply styles.listItem would return its ID (number)

This method internally uses StyleSheetRegistry.getStyleByID(style) to resolve style objects represented by IDs. Thus, an array of style objects (instances of StyleSheet.create), are individually resolved to, their respective objects, merged as one and then returned. This also explains the alternative use.