首页 > 解决方案 > React Native Styles:多个 StyleSheet.create() 与引用包含所有样式的外部对象之间的性能差异

问题描述

在 react native 组件中,我的按钮有多个变体。大小、填充(实心、轮廓、透明)和皮肤(主要、次要、警告、信息等)以及其他几个变体。

这三种方法之间有什么性能差异吗?另外,推荐的方法是什么?

(1)创建多个样式表- 每个变体的交叉点可能有 20-30 个对象

const getStyles = () => {
  // Solid Fill
  const solidPrimary = StyleSheet.create({
    base: {
      color: "blue"
    },
    loading: {
      color: "darkblue"
    },
    disabled: {
      color: "darkblue"
    }
  });

  const solidSecondary = StyleSheet.create({
    base: {
      color: "lightblue"
    },
    loading: {
      color: "skyblue"
    },
    disabled: {
      color: "skyblue"
    }
  });

  // Outline Fill
  const outlinePrimary = StyleSheet.create({
    base: {
      color: "white"
      borderColor: "blue"
    },
    loading: {
      color: "white"
      borderColor: "darkblue"
    },
    disabled: {
      color: "white"
      borderColor: "darkblue"
    }
  });
  // etc.

  return {
    solid: {
      primary: solidPrimary,
      secondary: solidSecondary
      // etc.
    },
    outline: {
      primary: outlinePrimary,
      secondary: outlineSecondary
      // etc.
    }
    // etc.
  }
}

vs. (2) 同上,但在一个对象中声明

const getStyles = () => {
  return {
    solid: {
      primary: StyleSheet.create({...}),
      secondary: StyleSheet.create({...}),
      // etc.
    },
    outline: {
      primary: StyleSheet.create({...}),
      secondary: StyleSheet.create({...}),
      // etc.
    }
    // etc.
  }
}

vs. (3) 同上,但引用了一个外部对象

const getStyles = ({fill, skin}) => {
  return StyleSheet.create({
    base: {
      // Referencing the object takes care of the fill and skin variants
      color: ...styleObj[fill][skin].base.color
      // other styles
    },
    loading: {
      color: ...styleObj[fill][skin].loading.color
      // other styles
    },
    disabled: {
      color: ...styleObj[fill][skin].disabled.color
      // other styles
    },

  });
}

// styleObj.js
  export const styleObj = {
    solid: {
      primary: {
        base: {...},
        loading: {...},
        disabled: {...},
      },
      secondary: {
        base: {...},
        loading: {...},
        disabled: {...},
      },
    },
    outline: {
      primary: {
        base: {...},
        loading: {...},
        disabled: {...},
      },
      secondary: {
        base: {...},
        loading: {...},
        disabled: {...},
      },
    },
    // etc.        
  }

标签: javascriptreact-nativestylesheetobject-literal

解决方案


推荐阅读