【问题标题】:Why can't I use StyleProp<ViewStyle> on my own component为什么我不能在我自己的组件上使用 StyleProp<ViewStyle>
【发布时间】:2019-12-09 20:44:08
【问题描述】:

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

style prop 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,我无法开始工作)

【问题讨论】:

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


    【解决方案1】:

    如果您不关心动画视图。

    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% 的答案。 ?


    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 2012-04-18
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多