[英]Importing Components with React/TypeScript
我想將測試組件導入主頁,但我不斷收到以下錯誤:
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"]
}
您的代碼不正確。 該錯誤與 ES6 箭頭函數(或 ES 模塊)的工作方式有關。
所以請允許我解釋一下:您收到 TypeScript 錯誤,因為您的Test
組件實際上並未return
您正在創建的 JSX。
export const Test:FC<Props> = ({ name }: Props) => ( <div>{name}</div> );
如果你用括號替換花括號,你的代碼可以正常工作。
此外,命名導出不等於default
導出。 在您的示例中,您通過export const Test
而不是default
導出Test
。
由於您尚未導出默認值,因此import Test from './test.tsx'
將不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.