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



我尝试在StyleSheet文件中使用一些variables

用户界面工作正常。但类型是错误的。

知道怎么解决这个问题吗?

type buttonStyle = (height: number, width: string, color: string) => ViewStyle;
export type Styles = {
button: buttonStyle;
};

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

这是来自类型的错误消息。

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
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>

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

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} />

我认为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;

无需定义样式类型。

最新更新