[英]Better way to add types to props in a functional component in NextJS Typescript project
I want to add types when there are multiple props.当有多个道具时,我想添加类型。 For ex:
例如:
export default function Posts({ source, frontMatter }) {
...
}
One way I found is to first create wrapper type and then create parameter type.我发现的一种方法是首先创建包装器类型,然后创建参数类型。 For ex:
例如:
type Props = {
source: string;
frontMatter: FrontMatter;
};
type FrontMatter = {
title: string;
author: string;
date: string;
};
export default function Posts({ source, frontMatter }:Props) {
...
}
But is there a way to avoid that extra Props
type because I'm using that for only this function.但是有没有办法避免额外的
Props
类型,因为我只将它用于这个 function。 I'm hoping to achieve something like this:我希望实现这样的目标:
export default function Posts({ source:string, frontMatter:FrontMatter }) {...}
i think its ur personal decision,ur first solution is true and if it works fine u can use it, i prefer using somthing like this:我认为这是你个人的决定,你的第一个解决方案是正确的,如果它工作正常你可以使用它,我更喜欢使用这样的东西:
interface PostProps {
source: string;
frontMatter: {
title: string;
author: string;
date: string;
}
}
export const Posts: React.FC<PostProps> = ({source,frontMatter}) => {
...
}
also ur suggested way can be like this:您建议的方式也可以是这样的:
export default function Posts({source,frontMatter}:{source: string,frontMatter:FrontMatter}) {
...
}
You can define the interface like below:-您可以定义如下界面:-
interface PostConfig {
source: string;
frontMatter: FrontMatterConfig;
}
interface FrontMatterConfig {
title: string;
author: string;
date: string;
}
And also mention the typing for the component:-并且还提到了组件的类型:-
const Posts: FunctionComponent<PostConfig> = ({
source,
frontMatter: { title, author, date }
}) => {
return (
<div>
<b>{source}</b>
<div>{title}</div>
<div>{author}</div>
<div>{date}</div>
</div>
);
};
Sample Code:- https://codesandbox.io/s/reverent-dijkstra-t4sfc?file=/src/App.tsx示例代码:- https://codesandbox.io/s/reverent-dijkstra-t4sfc?file=/src/App.tsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.