[英]Better way to add types to props in a functional component in NextJS Typescript project
當有多個道具時,我想添加類型。 例如:
export default function Posts({ source, frontMatter }) {
...
}
我發現的一種方法是首先創建包裝器類型,然后創建參數類型。 例如:
type Props = {
source: string;
frontMatter: FrontMatter;
};
type FrontMatter = {
title: string;
author: string;
date: string;
};
export default function Posts({ source, frontMatter }:Props) {
...
}
但是有沒有辦法避免額外的Props
類型,因為我只將它用於這個 function。 我希望實現這樣的目標:
export default function Posts({ source:string, frontMatter:FrontMatter }) {...}
我認為這是你個人的決定,你的第一個解決方案是正確的,如果它工作正常你可以使用它,我更喜歡使用這樣的東西:
interface PostProps {
source: string;
frontMatter: {
title: string;
author: string;
date: string;
}
}
export const Posts: React.FC<PostProps> = ({source,frontMatter}) => {
...
}
您建議的方式也可以是這樣的:
export default function Posts({source,frontMatter}:{source: string,frontMatter:FrontMatter}) {
...
}
您可以定義如下界面:-
interface PostConfig {
source: string;
frontMatter: FrontMatterConfig;
}
interface FrontMatterConfig {
title: string;
author: string;
date: string;
}
並且還提到了組件的類型:-
const Posts: FunctionComponent<PostConfig> = ({
source,
frontMatter: { title, author, date }
}) => {
return (
<div>
<b>{source}</b>
<div>{title}</div>
<div>{author}</div>
<div>{date}</div>
</div>
);
};
示例代碼:- https://codesandbox.io/s/reverent-dijkstra-t4sfc?file=/src/App.tsx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.