代码之家  ›  专栏  ›  技术社区  ›  Ilja

扩展flow“type Props”以包括来自其他组件的道具类型?

  •  3
  • Ilja  · 技术社区  · 6 年前

    我有以下组件,主要依赖于 Image 来自react native

    // @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 引发错误

    [流量]属性 风格 (在道具中找不到属性)常量样式:any

    我知道在typescript中,我可以将接口扩展到图像一,流中是否有一些东西可以让我的道具继承所有类型 形象 以某种方式我如何从react native导入此类类型?

    编辑 我发现了一个叫做交叉点类型的概念,并尝试了这个

    import { Image, type Image as ImageProps } from "react-native";
    type Props = ImageProps & {
      width: number,
      ratio: number
    };
    

    但style仍在抛出一个错误,尽管不同

    [流量]属性 风格 (无法在的任何成员上访问属性 交叉点类型交叉点成员1:ImageProps错误:属性 风格 在React组件成员2中未找到属性:对象类型 错误:属性 风格 在对象类型(const)中找不到属性 样式:任意

    1 回复  |  直到 6 年前
        1
  •  5
  •   jevakallio    6 年前

    不幸的是,React Native在使用流类型的方式上并不是百分之百一致的。

    如果你想对 Text 组件,您只需从内部 TextProps 由全局Haste命名空间提供的模块,并使用流类型联合创建您自己的超类型:

    import type { TextProps } from 'TextProps';
    
    type ExtendedTextProps = TextProps & {
      additionalProp: string
    };
    

    也就是说,没有 ImageProps 要导入的模块。如果你看看 Image (iOS) component types ,它们仍然表示为PropTypes。

    此时,我相信,为自定义图像组件添加完整类型覆盖的最简单方法是查看图像组件的proptype并手动将其转换为流类型。一些更复杂的字段类型,如 ImageSource ImageStyle 已存在为flowtypes。

    我不确定核心团队的意图是什么,但可能值得考虑将类型def贡献给本地用户,并为未来的用户解决这个问题。