typescript - 为什么我不能使用 StyleProp在我自己的组件上
问题描述
我正在使用 TypeScript/Vscode 对我的 React Native 应用程序进行编码。我希望我的自定义组件的代码完成样式就像 React Native 自己的View
组件一样。
style
propView
定义如下:
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)
我究竟做错了什么?
(只是为了澄清:该样式在运行时确实可以完美运行,只是代码完成/智能感知,我无法开始工作)
解决方案
如果您不关心动画视图。
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% 的答案。
推荐阅读
- javascript - 如何在 d3pie 中更改饼图的颜色
- json - Swift 4 从自定义 JSON 对象解码到不同的模型
- node.js - 如何设置新的键 Redis 回调
- python - 为什么我在 Jupyter Notebook 的所有列中只获得 NaN 值?
- php - 如何获取经过身份验证的用户可用的路由
- razor - Kendo UI 网格的自定义行/复选框模板
- postgresql - postgres - 简化数据库操作
- php - 如何修复我的 php 代码中的 Mysqli 错误 #1064?
- opencv - 如何在没有手动实验的情况下找到 logPolar Magnitude 比例参数
- selenium - 无法通过 xpath 集合获取 Web 元素 (Workfusion)