VSCode中的typescript編譯器,目前在TypeScript React 4.4.2指出了一個TS(2339)錯誤。Property 'Col' does not exist on type 'FC<GridProps>'.
我試著在GridProps中添加這個道具:
export type GridProps = {
children: ReactNode;
className?: 字串。
Col: JSX.Element。
};
但是,錯誤仍然顯示。我認為這是因為Grid組件沒有被初始化。我見過這種用其他未初始化的組件來擴展一個主組件的慣例,如Grid.Col = Col(見截圖),當它被實作時,它實際上是可行的:
<Grid.Col>
{/* */}。
</Grid.Col>
在這種情況下,如何消除TS(2339)錯誤?
注意:我以前見過這樣的組件,編譯器并沒有拋出,而且它們的道具型別中也沒有事件指定Component道具。
首先,你需要洗掉GridProps中的Col,Col不是一個道具。
export type GridProps = {
children: ReactNode;
className?: string;
};
其次,為了讓TS高興,我們需要指定網格組件的型別。
export type GridType = FC< GridProps> & {
Col: FC<{}> 。
};
以及實作:
export const Grid: GridType = (({ className, children }) => {
return <div className={className}> {children}</div> 。
}) as GridType;
Grid.Col = () => {
return <p>hello</p> ;
};
在此演示:
https://codesandbox.io/s/practical-haze-w3o57?file=/src/App.tsx
另一種方法是,使用Function,而不是Arrow Function與React.FC<>。
export type GridProps = {
children: ReactNode;
className?: string;
};
export function Grid({ className, children }: GridProps) {
return <div className={className}> {children}</div> 。
}
Grid.Col = () => {
return <p>hello</p> ;
};
https://codesandbox.io/s/optimistic-pike-1ir9i?file=/src/App.tsx
另一種方法是,不要使用React.FC。你可以在這里讀到更多關于這個的資訊。TypeScript React.FC<Props> 混淆
export type GridProps = {
children: ReactNode;
className?: string;
};
export const Grid = ({ className, children }: GridProps) => {
return <div className={className}> {children}</div> 。
};
Grid.Col = () => {
return <p>hello</p> ;
};
export default function App() {
return (
<div className="App"/span>>
<h1>Hello CodeSandbox</h1>
<h2>開始編輯,看到一些神奇的事情發生!</h2>/span>
<Grid>/span>
<Grid.Col />>
</Grid>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/307002.html
標籤:
上一篇:如何驗證每個瀏覽器的點擊率?



uj5u.com熱心網友回復: