在React Native StyleSheet中使用带有Typescript的函数

时间:2019-09-24 16:11:31

标签: typescript react-native

通常我想做类似的事情

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<any> | NamedStyles<Style>'.

有什么想法如何处理吗?

2 个答案:

答案 0 :(得分:0)

我认为StyleSheet不支持在其键中包含功能。它的作用是像从网络上发布样式表一样。我怀疑您之前的操作不受支持,但是现在您正在使用TypeScript,它正在强制执行此操作。

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

答案 1 :(得分:0)

StylesSheet不支持使用功能,但是您可以改用Object或Function并使用以下类型之一输入返回值 ViewStyle | TextStyle | ImageStyle

例如

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