首页 文章

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

提问于
浏览
0

我在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 回答

  • 1

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

    1style={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
        }
    });
    

相关问题