Använda en funktion på stylesheet typescript react native
Jag försöker använda några variabler i min StyleSheet-fil.
UI fungerar bra. Men typen är fel.
Någon idé om hur man löser detta?
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,
}),
});
Detta är felmeddelandet från typen.
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
Svar #1
Du kan skapa en const-stil med StyleSheet.create() utanför din komponent:
const styles = ((height: number, width: string, color: string)) => StyleSheet.create({
btn: {
height: height,
width: width,
backgroundColor: color,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 10,
}
});
och kalla det sedan så här i din komponent:
<Button style={styles(height: height, width: width, color: color).btn} />
Svar #2
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,
}),
});
lägg till typen any som den här,
StyleSheet.create<Styles | any>
