【问题标题】:Component fails to auto import types from index.d.ts file in React Native组件无法从 React Native 中的 index.d.ts 文件自动导入类型
【发布时间】:2020-08-27 20:32:51
【问题描述】:

我有一个名为 ColorBox 的组件,在它的文件夹中我有组件本身、它的样式和一个索引文件以及我的类型的 index.d.ts 文件:

  ColorBox
   |- Colorbox.tsx
   |- index.ts
   |- styles.ts
   |- index.d.ts

这是我的index.d.ts 文件:

export interface IProps {
  colorName: string;
  colorHex: string;
}

export interface IBGColor {
  backgroundColor: string;
}

这是我的ColorBox.tsx 组件:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

import styles from './styles';

const ColorBox: React.FC<IProps> = ({ colorName, colorHex }) => {
  const boxColor: IBGColor = {
    backgroundColor: colorHex,
  };

  return (
    <View style={[styles.box, boxColor]}>
      <Text style={styles.boxText}>{colorName}</Text>
    </View>
  );
};

export default ColorBox;

问题是 IPropsIBGColor 类型不会自动从 index.d.ts 文件导入,它是如何工作的,我一直在阅读有关 TypeScript 的文章,有人提到如果你放一个 @987654330 @ 模块内的文件,TypeScript 将依赖它并尝试从该文件中查找类型,但为什么它在我的组件中不起作用?

我应该在我的模块中显式导入使用的类型吗?如果是这样,那么index.d.ts文件给我们带来了什么好处?

我也使用常规的 react-native init 项目,而不是任何其他花哨的样板!

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    index.d.ts 用于声明全局类型,并且由于该类型在您的整个项目中都可用,因此您无需将其导入组件中,也无需将其导出到index.d.ts 文件中,只需使用它即可。

    【讨论】:

    • 但它不起作用,当我尝试在我的组件内部使用它时,VsCode 在它下面放了一些红线并说Cannot find name 'IProps'.ts(2304)
    猜你喜欢
    • 2019-02-25
    • 1970-01-01
    • 2020-11-04
    • 2018-11-26
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 2023-04-05
    • 2019-12-22
    相关资源
    最近更新 更多