【问题标题】:Using functions within React Native StyleSheet with Typescript在带有 Typescript 的 React Native StyleSheet 中使用函数
【发布时间】:2019-09-24 16:11:31
【问题描述】:

很多时候我想做类似的事情

const styles = StyleSheet.create({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

现在这不起作用,因为我得到了Type '(size: number) => { width: number; height: number; }' is not assignable to type 'ViewStyle | TextStyle | ImageStyle'。我试过做类似的事情

interface Style {
  square: (width: number) => ViewStyle
}

const styles = StyleSheet.create<Style>({
  square: (size: number) => ({
    width: size,
    height: size,
  }),
})

然后我得到Type 'Style' does not satisfy the constraint 'NamedStyles&lt;any&gt; | NamedStyles&lt;Style&gt;'.

任何想法如何处理这个问题?

【问题讨论】:

    标签: typescript react-native


    【解决方案1】:

    我认为 StyleSheet 不支持在其键中包含功能。它的作用类似于来自网络的样式表。我怀疑您之前所做的事情不受支持,但现在您使用的是 TypeScript,它正在强制执行此操作。

    https://facebook.github.io/react-native/docs/stylesheet.html

    【讨论】:

      【解决方案2】:

      StylesSheet 不支持使用函数,但您可以使用 Object 或 Function 代替,并使用其中一种类型键入返回值 ViewStyle | 文字样式 | 图像样式

      例如

      const styles = {
          square: (size: number): ViewStyle => ({
              width: size,
              height: size,
          })
      };
      

      【讨论】:

        猜你喜欢
        • 2019-03-17
        • 2021-04-23
        • 1970-01-01
        • 2017-03-04
        • 2023-04-04
        • 2021-11-22
        • 2017-04-27
        • 1970-01-01
        • 2020-10-12
        相关资源
        最近更新 更多