我认为在 React 中允许将数组分配给样式?
像这样:
import React from 'react';
import { Text } from "react-native";
// ...
render() {
const textStyles = [styles.text];
return <Text style={textStyles}>Some Text</Text>;
}
但是 TSLint 提示这条线:
[ts]
Type 'RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }>[]' is not assignable to type 'StyleProp<TextStyle>'.
Type 'RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }>[]' is not assignable to type 'RecursiveArray<false | TextStyle | RegisteredStyle<TextStyle> | null | undefined>'.
Types of property 'pop' are incompatible.
Type '() => RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }> | undefined' is not assignable to type '() => StyleProp<TextStyle>'.
Type 'RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }> | undefined' is not assignable to type 'StyleProp<TextStyle>'.
Type 'RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }> | undefined' is not assignable to type 'StyleProp<TextStyle>'.
Type 'RegisteredStyle<{ color: string; fontWeight: string; fontSize?: undefined; padding: number; textAlign: "center"; } | { color: string; fontSize: number; fontWeight?: undefined; padding: number; textAlign: "center"; }>' is not assignable to type 'StyleProp<TextStyle>'.
这里发生了什么? React Native 的类型错了吗?或者我是否应该为 RN 样式对这些数组进行类型转换?
最佳答案
您可以测试一些方法来解决您的问题,希望能奏效:
1 :style={styles.yourStyle as any}
也许你应该这样做!
2 :我看不到你如何实现你的风格,但你可以测试这样的东西?
import { StyleSheet, TextStyle, ViewStyle } from "react-native";
type Style = {
container: ViewStyle;
title: TextStyle;
icon: ImageStyle;
};
export default StyleSheet.create<Style>({
container: {
flex: 1
},
title: {
color: red
},
icon: {
width: 10,
height: 10
}
});
关于TypeScript 和 React Native : Are the type definitions for RN styles wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53639013/