【问题标题】:Importing Components with React/TypeScript使用 React/TypeScript 导入组件
【发布时间】:2021-04-19 17:08:00
【问题描述】:

我想将测试组件导入主页,但我不断收到以下错误:

Module '"/.../src/components/Test"' has no default export. Did you mean to use 'import { Test } from "/.../src/components/Test"' instead?

在测试组件中,我在导出测试时不断收到以下错误:

Type '({ name }: Props) => void' is not assignable to type 'FC<Props>'.
  Type 'void' is not assignable to type 'ReactElement<any, any> | null'

测试组件

import React,{FC} from 'react';

interface Props {
  name: string;
}
export const Test:FC<Props> = ({ name }: Props) => {
  <div>{name}</div>
};

首页组件

import React from 'react';
import Test from './Test'

export const Home = () => {
  <div><Test name="example" /></div>
};

tsconfig.json

{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": ["src"]
}

【问题讨论】:

    标签: javascript reactjs typescript tsx react-tsx


    【解决方案1】:

    您的代码不正确。该错误与 ES6 箭头函数(或 ES 模块)的工作方式有关。

    所以请允许我解释一下:您收到 TypeScript 错误是因为您的 Test 组件实际上并不是您正在创建的 JSX return

    export const Test:FC<Props> = ({ name }: Props) => (
      <div>{name}</div>
    );

    如果你用括号替换花括号,你的代码可以正常工作。

    此外,命名导出不等于default 导出。在您的示例中,您通过export const Test 而不是default 导出Test

    由于您尚未导出默认值,import Test from './test.tsx' 将不起作用。

    我建议你read up on ES ModulesES6 arrow functions

    【讨论】:

    • 愿意解释反对意见吗?它回答了问题,并提供了资源。
    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2017-09-06
    • 2019-08-15
    • 2021-06-28
    相关资源
    最近更新 更多