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>
从代码质量角度:
从性能角度:
这一常量定义了当前平台上的最细的宽度。可以用作边框或是两个元素间的分隔线。例如:
这一常量始终是一个整数的像素值(线看起来会像头发丝一样细),并会尽量符合当前平台最细的线的标准。然而,你不能把它“视为一个常量”,因为不同的平台和不同的屏幕像素密度会导致不同的结果。
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.
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', }, });
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:
StyleSheet<span class="token punctuation">.</span><span class="token function">flatten<span
class="token punctuation">(</span></span><span class="token punctuation">[</span>styles<span
class="token punctuation">.</span>listItem<span class="token punctuation">,</span>
styles<span class="token punctuation">.</span>selectedListItem<span
class="token punctuation">])</span><span class="token comment" spellcheck="true">
// returns { flex: 1, fontSize: 16, color: 'green' }
Alternative use:
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.