首页 > 解决方案 > 为什么我不能使用 StyleProp在我自己的组件上

问题描述

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

stylepropView定义如下:

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)

我究竟做错了什么?

(只是为了澄清:该样式在运行时确实可以完美运行,只是代码完成/智能感知,我无法开始工作)

标签: typescriptreact-nativevisual-studio-codeintellisensetypescript3.0

解决方案


如果您不关心动画视图。

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

也在这里投票,因为我在这里找到了 99% 的答案。



推荐阅读