[英]Extending flow `type Props` to include prop types from another component?
我有以下組件,主要依賴於來自react-native的Image
// @flow
import React from "react";
import { Image } from "react-native";
import { deviceWidth } from "../services/device";
type Props = {
width: number,
ratio: number
};
class RatioImage extends React.Component<Props> {
render() {
const { width, ratio, style, ...props } = this.props;
return (
<Image
{...props}
style={[
{
width: deviceWidth * (width / 100),
height: deviceWidth * (width / 100) * ratio
},
style
]}
/>
);
}
}
export default RatioImage;
我能夠鍵入注釋我自己的道具,但在上面的例子中, style
會引發錯誤
[flow]屬性
style
(Props中找不到屬性)const樣式:any
我知道在打字稿中我可以將界面擴展到Image one,我可以使用流程中的某些內容,以便讓我的道具以某種方式從Image
繼承所有類型嗎? 我怎么能從react-native導入這樣的類型?
編輯我發現了關於交叉類型的概念,並嘗試了這一點
import { Image, type Image as ImageProps } from "react-native";
type Props = ImageProps & {
width: number,
ratio: number
};
但風格仍然是一個錯誤,雖然不同
[flow]屬性
style
(無法在交集類型交集的任何成員上訪問屬性成員1:ImageProps錯誤:屬性style
在React組件中找不到屬性成員2:對象類型錯誤:屬性style
在對象類型中找不到屬性)const樣式:任何
不幸的是,React Native在使用flowtypes的方式上並不是100%一致的。
如果您嘗試對Text
組件執行相同操作,則只需從全局Haste命名空間提供的內部TextProps
模塊中導入類型定義,並使用Flow類型聯合創建自己的超類型:
import type { TextProps } from 'TextProps';
type ExtendedTextProps = TextProps & {
additionalProp: string
};
也就是說,沒有ImageProps
模塊供您導入。 如果您查看Image
(iOS)組件類型 ,它們仍然表示為PropTypes。
在這個時候,我相信,為自定義圖像組件添加完整類型覆蓋的最簡單方法是查看Image組件的PropTypes並手動將它們轉換為Flow類型。 一些更復雜的字段類型(如ImageSource和ImageStyle)已作為流類型存在。
我不確定核心團隊的意圖是什么,但是考慮將類型defs貢獻給React Native本身並為未來的用戶解決這個問題可能是值得的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.