为什么我不能在自己的组件上使用StyleProp <ViewStyle>

时间:2019-08-01 09:27:02

标签: typescript react-native visual-studio-code intellisense typescript3.0

我正在使用TypeScript / Vscode编码我的React Native应用程序。我希望我的自定义组件上的代码能够完成样式,就像React Native自己的View组件一样。

style属性View的定义如下:

style?: StyleProp<ViewStyle>;

当我在自己组件的道具上尝试时:

type MyViewProps = { style?:StyleProp<ViewStyle> }
class MyView extends Component<MyViewProps>{ ... }

并尝试以我在常规视图上使用style的方式使用它:

<MyView style={{top:-20}}/>

我收到以下错误:

Type '{ style: { top: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.
  Property 'style' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.ts(2322)

我在做什么错了?

(为澄清起见:样式确实在运行时可以完美地工作,只是代码完成/ IntelliSense我无法使用)

1 个答案:

答案 0 :(得分:3)

如果您不关心动画视图。

type MyViewProps = { style?: ViewStyle };


如果您确实关心Animated.View

type MaybeAnimated<T> = T | Animated.Value;
type AnimatedScalar = string | number;

type AnimatedStyle<T> = {
  [Key in keyof T]: T[Key] extends AnimatedScalar
    ? MaybeAnimated<T[Key]>
    : T[Key] extends Array<infer U>
    ? Array<AnimatedStyle<U>>
    : AnimatedStyle<T[Key]>;
};

像这样使用它。

type MyViewProps = { style?: AnimatedStyle<ViewStyle> };

转到upvote here too,因为我在这里找到了99%的答案。 ?


相关问题