首页 文章

扩展流`类型道具`以包含来自另一个组件的道具类型?

提问于
浏览
2

我有以下组件主要依赖于来自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]属性样式(Props中找不到属性)const样式:any

我知道在打字稿中我可以将界面扩展到Image one,是否有一些我可以使用的流程,以使我的道具从某种方式继承 Image 的所有类型?我怎么能从react-native导入这样的类型?

EDIT 我发现了关于交叉类型的概念,并试过这个

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

但风格仍然是一个错误,虽然不同

[flow]属性样式(无法在交集类型交集的任何成员上访问属性成员1:ImageProps错误:属性样式在React组件中找不到属性成员2:对象类型错误:属性样式在对象类型中找不到属性)const样式: 任何

1 回答

  • 2

    不幸的是,React Native在使用flowtypes的方式上并不是100%一致的 .

    如果您尝试对 Text 组件执行相同操作,则只需从全局Haste命名空间提供的内部 TextProps 模块中导入类型定义,并使用Flow类型联合创建自己的超类型:

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

    也就是说,没有 ImageProps 模块可供您导入 . 如果您查看Image (iOS) component types,它们仍然表示为PropTypes .

    在这个时候,我相信,为自定义图像组件添加完整类型覆盖的最简单方法是查看Image组件的PropTypes并手动将它们转换为Flow类型 . 一些更复杂的字段类型(如ImageSourceImageStyle)已作为流类型存在 .

    我不确定核心团队的目的是什么,但是可能值得考虑将类型defs贡献给React Native本身并为未来用户解决这个问题 .

相关问题