React Native FAQ: 内嵌样式与StyleSheet的区别

从vue转react native 开发后,这个问题困扰了我很久。类似这样的内嵌样式写起来非常爽:

<Text style={{fontSize: 16, marginHorizontal: 8}}/>

但是我的 eslint 却不建议我创建内嵌样式。通过 StyleSheet 创建样式非常繁琐:

const styles = StyleSheet.create({
  text: {
    fontSize: 16,
    marginHorizontal: 8
  },
});

这样创建完之后,然后才能再去引用:

<Text style={styles.text}/>

我们在开发中需要写大量的 fontSizemarginpadding 等等样式,但是这种样式往往只需要用一次,我不明白为什么要禁止内嵌样式。

经过了一番查找之后,我找到了原因。

在早期的官方文档中,给出了需要使用 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>
  );
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值