簡體   English   中英

擴展流`類型道具`以包含來自另一個組件的道具類型?

[英]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類型。 一些更復雜的字段類型(如ImageSourceImageStyle)已作為流類型存在。

我不確定核心團隊的意圖是什么,但是考慮將類型defs貢獻給React Native本身並為未來的用戶解決這個問題可能是值得的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM