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

时间:2018-12-05 18:57:46

标签: typescript react-native typescript-typings typescript-types

我认为在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样式?

2 个答案:

答案 0 :(得分:0)

您可以测试一些解决问题的方法,希望这项工作:

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
    }
});

答案 1 :(得分:0)

自创建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>;