TypeScript 和 React Native:RN 样式的类型定义是否错误?

TypeScript and React Native: Are the type definitions for RN styles wrong?

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

由于您创建了 textStyles 变量,您需要为其添加类型:

const textStyles: StyleProp<TextStyle> = [styles.a, styles.b];
return <Text style={textStyles}>Some Text</Text>;

但通常你会直接应用样式:

return <Text style={[styles.a, styles.b]}>Some Text</Text>;