reactjs - 属性 'width' 在类型 'StyleProp' 上不存在
我正在开发一个使用 TypeScript 构建的 React Native 应用。我有一个组件,它使用与 View 元素相同的 props。如果存在 style prop,我需要提取 width 以便将计算出的宽度传递给子组件。一个简化的示例可能如下所示。
const WidgetContainer = ({ style = {}, ...props }: ViewProps) => {
const { width = DEFAULT_WIDTH } = style;
const widgetWidth = Math.floor(width / 3);
return (
<View style={[style, { width }]} {...props}>
<WidgetRow widgetWidth={widgetWidth} />
</View>
);
};
一切都使用绝对定位,我们可以安全地假设只会使用数值宽度。这应该可行。Expo 可以正常运行代码,看起来没有任何异常。
但是如果我显式地进行类型检查,无论是在 VS Code 中还是通过运行 tsc,我都会在第二行得到这个错误:
Property 'width' does not exist on type 'StyleProp<ViewStyle>'
说实话,这令人困惑。我在整个代码库中都在 View 样式中使用 width。如果我查看 react-native 类型的声明文件,我可以看到 ViewStyle:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-native/index.d.ts#L1963
它 继承 FlexStyle:
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-native/index.d.ts#L692
而 width 就在那里!!
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-native/index.d.ts#L743
我感到很困惑。这是一个错误吗?还是我忽略了什么愚蠢的事情?
相关版本:
- 反应:17.0.38
- react-native: 0.64.3
- tsc: 4.3.5
- node_modules/expo: 44.0.6
- expo CLI:5.4.9