【问题标题】:What is the use of Stylesheet in react-native样式表在 react-native 中有什么用
【发布时间】:2019-10-13 07:48:00
【问题描述】:

我正在使用 react-native 构建一个 android 应用程序。

我的 JSX 的一部分包括,

<Text style={{ color: "red" }}> Styled using style prop !! </Text>
<Text style={styles.colorRed}> Styled uisng StyleSheet !!</Text>

和,

const styles = StyleSheet.create({
  colorRed: {
    color: "red"
  }
})

Text 组件似乎呈现相同的样式(至少在 android 平台上),

docs 建议使用StyleSheet 模块。 我的问题是,我应该什么时候使用StyleSheet 模块?

【问题讨论】:

标签: react-native react-native-android


【解决方案1】:

您应该使用 StyleSheet 而不是内联样式。

好处

  • 通过将样式从渲染函数中移开,您正在制作 代码更容易理解。

  • 为样式命名是为底层添加意义的好方法
    渲染函数中的组件。

  • 与普通样式不同,样式表只通过网桥发送一次 render() 中的对象。

但是,您可以使用 style 属性来内联添加样式。但是,这不是最佳实践,因为它可能很难阅读代码。您可能不想使用内联样式表的一个原因是减少代码中的重复量。

第一个内联样式。

示例

<Text style={{ color: "red" }}> Styled using style prop !! </Text>

第二个是使用StyleSheet,您创建一个样式对象并单独引用每个样式。这带来了样式与渲染方法的分离,并帮助您组织代码。

示例

    <Text style={styles.colorRed}> Styled uisng StyleSheet !!</Text>
    // initialize stylesheet
    const styles = StyleSheet.create({
      colorRed: {
        color: "red"
      }
})

什么时候应该使用内联样式,例如,如果您有基本样式表,并且您有多个具有相同样式但有一两个属性发生变化的组件,那么您可以使用内联样式

示例

    <Text style={[CommonStyles.textLightGrey, { alignSelf: 'flex-end' }]} >Balance</Text>
    <Text style={[CommonStyles.textLightGrey, { alignSelf: 'center' }]} >Balance</Text>
// It is my common or base stylesheet
export default StyleSheet.create({
       textLightGrey: {
        fontSize: 12,
        color: COLORS.lightgrey
    },

});

【讨论】:

    【解决方案2】:

    是的,您应该更喜欢样式表而不是内联样式。 当您在样式表中设置样式时,您会直接在您的模拟器/设备上得到相应的错误,因此您会知道您的错误(如果有的话),而您的代码可能会在内联样式中搞砸!

    【讨论】:

      猜你喜欢
      • 2022-12-14
      • 1970-01-01
      • 2020-09-21
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多