![](/img/trans.png)
[英]Function Props with Functional component - is not a function (React + Typescript)
[英]Sending Props to functional component : TypeScript
我有這樣定義的自定義接口
interface Meeting {
Subject: string;
Organizer: string;
StartTime: string;
EndTime: string;
Participants: Participant[] | null;
}
interface Participant {
Name: string;
Title: string;
}
然后我有一個
const meetings: Meeting[] = // array of Meeting objects
現在我嘗試這樣發送
export const App = ():JSX.Element => {
return <div className="app-container">
<MainView info={meetings}/>
<SideBar/>
</div>
}
我得到的錯誤是“信息”,它顯示
Type '{ info: Meeting[]; }' is not assignable to type 'IntrinsicAttributes & Meeting[]'.
Property 'info' does not exist on type 'IntrinsicAttributes & Meeting[]'.ts(2322)
這里有什么問題,我該如何發送這個道具?
此外,在接收組件中有
export const MainView = ({info}: Meeting[]):JSX.Element => {return <></>}
並且錯誤再次出現在“信息”處
Property 'info' does not exist on type 'Meeting[]'.ts(2339)
Props 是 object,info 是 object 的一個屬性。 所以你可以像這樣指定類型:
export const MainView = ({ info }: { info: Meeting[] }): JSX.Element =>
或者,還有一個用於 function 組件的輔助類型FC
:
import { FC } from 'react';
export const MainView: FC<{ info: Meeting[] }> = ({ info }) =>
請注意, FC
會自動添加children
作為可能的道具,這可能不是我們所希望的。
這是因為 JSX.Element 中的第一個參數是指整個prop
object: 所以當你解壓info
鍵時,你需要這樣定義類型:
export const MainView = ({ info }: { info: Meeting[] }):JSX.Element => {return <></>}
為了更清楚,單獨定義 MainView 的 props 是有意義的:
interface MainViewProps {
info: Meeting[];
}
export const MainView = ({ info }: MainViewProps):JSX.Element => {return <></>}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.