从vue转react native 开发后,这个问题困扰了我很久。类似这样的内嵌样式写起来非常爽:
<Text style={{fontSize: 16, marginHorizontal: 8}}/>
但是我的 eslint 却不建议我创建内嵌样式。通过 StyleSheet
创建样式非常繁琐:
const styles = StyleSheet.create({
text: {
fontSize: 16,
marginHorizontal: 8
},
});
这样创建完之后,然后才能再去引用:
<Text style={styles.text}/>
我们在开发中需要写大量的 fontSize
、margin
、padding
等等样式,但是这种样式往往只需要用一次,我不明白为什么要禁止内嵌样式。
经过了一番查找之后,我找到了原因。
在早期的官方文档中,给出了需要使用 StyleSheet
的原因。
Performance:
- Making a stylesheet from a style object makes it possible to refer to it by ID instead of creating a new style object every time.
- It also allows to send the style only once through the bridge. All subsequent uses are going to refer an id (not implemented yet).
当界面元素更新的时候,内嵌样式都要重新被计算一次,但是使用 StyleSheet
之后,这部分样式就不需要被重新计算。
但是,在某些情况下你可能依然需要内嵌样式,例如我项目中的这个例子:
interface Props {
status?: number;
}
const StatusTag = (props: Props) => {
const statusColor = ['#4CAF50', '#F44336', '#448AFF', '#FF5722'];
const statusText = ['草稿', '评价中', '评价完成', '已发布'];
return (
<Text
style={[
styles.tag,
{
color: statusColor[props.status - 1],
borderColor: statusColor[props.status - 1],
},
]}>
{statusText[props.status - 1]}
</Text>
);
};