在样式表typescript react native上使用函数

b5lpy0ml  于 2022-11-25  发布在  React
关注(0)|答案(3)|浏览(118)

我尝试在我的StyleSheet文件中使用一些variables
UI工作正常。但类型错误。
你知道怎么解决吗?
第一个
这是来自类型的错误消息。

Type 'Styles' does not satisfy the constraint 'NamedStyles<any> | NamedStyles<Styles>'.
  Type 'Styles' is not assignable to type 'NamedStyles<Styles>'.
    Types of property 'button' are incompatible.
      Type 'buttonStyle' is not assignable to type 'ViewStyle | TextStyle | ImageStyle
7ajki6be

7ajki6be1#

export default StyleSheet.create<Styles | any>({
  button: (height: number, width: string, color: string) => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
});

添加诸如this之类任何类型,

StyleSheet.create<Styles | any>
5t7ly7z5

5t7ly7z52#

我认为StyleSheet不包含函数类型。所以我用这个方法修复了这个错误。
样式文件

import type { ViewStyle } from 'react-native';

const styles = {
  button: (height: number, width: string, color: string): ViewStyle => ({
    height: height,
    width: width,
    backgroundColor: color,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 10,
  }),
};

export default styles;

无需定义样式类型。

xj3cbfub

xj3cbfub3#

您可以在组件外部使用StyleSheet. create()创建常量样式:

const styles = ((height: number, width: string, color: string)) => StyleSheet.create({
    btn: {
        height: height,
        width: width,
        backgroundColor: color,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 10,
    }
});

然后在组件中这样调用它:

<Button style={styles(height: height, width: width, color: color).btn} />

相关问题