【问题标题】:Image type in typescript打字稿中的图像类型
【发布时间】:2021-01-12 03:54:31
【问题描述】:

大家好,SourceStyle 的类型应该是什么

源将包含图像文件位置。像这样的

source = require('../../../assets/user.png')

样式会有一个样式对象,但不确定我写style: Object是否正确。

export interface AvatarProps {
    source?: any;  <<<<< Don't want to use any
    style?: any;   <<<<< Don't want to use any
    shape?: string;
    ImageComponent?: React.ComponentType;
    size?: 'tiny' | 'small' | 'medium' | 'large' | 'giant';
}

export const Avatar: FunctionComponent<AvatarProps> = ({
    shape,
    style,
    size = 'medium',
    ImageComponent,
    source = require('../../../assets/user.png'),
}) => {
    return (
        <View>
         ....
        </View>
    );
};

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    source 只是一个字符串。不需要导入二进制数据;通常我们只需要一个 URL。

    对于style,由于你使用的是React,你可以使用React.CSSProperties作为它的类型。

    【讨论】:

    • 谢谢React.CSSProperties这有帮助
    【解决方案2】:

    您可以使用 react-native 中的 ImageSourcePropTypeImageStyle

    interface AvatarProps {
      style: StyleProp<ImageStyle>;
      source: ImageSourcePropType;
    } 
    

    对于sourceImageSourcePropType 将覆盖远程和本地图像

    <MyAvatar source={{ uri: 'https://placehold.it/50x50' }} />
    <MyAvatar source={require('../assets/hello-world.png} />
    

    提示:如果您查看 React Native 文档,它可能会告诉您类型。 https://reactnative.dev/docs/image#source 提到类型ImageSourcePropType

    对于样式,https://reactnative.dev/docs/image#style 没有明确提及类型,但是,如果您使用 VSCode 并将鼠标悬停在某个道具上,它将显示其所需的类型。

    如果悬停不起作用,请使用命令 (⌘) 并单击道具,它会显示所需的类型。

    export interface ImageProps extends ImagePropsBase {
        /**
         *
         * Style
         */
        style?: StyleProp<ImageStyle>;
    }
    

    【讨论】:

      【解决方案3】:

      文件位置只是一个字符串,所以source 的类型是string。对于style,这取决于。如果它是您认为将被重用或扩展的对象,最好创建一个接口并使用该类型。尽量避免使用诸如object 之类的一般类型,从而利用打字系统。

      【讨论】:

      • 不客气。如果您对答案感到满意,可以单击复选标记。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 2020-10-12
      • 2021-06-03
      • 2021-05-08
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多