react中用FC创建符合TypeScript的组件
https://medium.com/@bobjunior542/effortlessly-use-react-fc-with-typescript-best-practices-91aa7fc057c7
React Function Components (FCs) have become a popular way to create reusable components in React applications. TypeScript, with its strong type system, can help to ensure that our React components are type-safe and less prone to errors. In this article, we’ll explore how to correctly use the React FC with TypeScript.
Import React and declare FC type
To use the React FC, we need to import React and declare the FC type. We can do this with the following code:
import React, { FC } from ‘react’;
Declare Props interface
Next, we need to declare an interface for the props that our FC will receive. This interface will define the shape of the props and their types. For example:
interface MyComponentProps {
name: string;
age: number;
}
Define FC with Props interface
With the Props interface defined, we can now use it to define our FC. We’ll use the FC type and pass in our Props interface as a generic type argument. For example:
const MyComponent: FC<MyComponentProps> = ({ name, age }) => {
return (
<div>
<h1>{name}</h1>
<p>{age}</p>
</div>
);
};
Use FC in JSX
Now that our FC is defined, we can use it in JSX just like any other component. For example:
<MyComponent name="John Doe" age={30} />
Optional Props and Default Values
In TypeScript, we can make props optional by adding a question mark after the prop name, and we can define default values for props using the equals sign. For example:
interface MyComponentProps {
name: string;
age?: number;
gender?: 'male' | 'female';
greeting: string;
}
const MyComponent: FC<MyComponentProps> = ({ name, age = 18, gender, greeting }) => {
return (
<div>
<h1>{greeting}, {name}!</h1>
{gender && <p>Gender: {gender}</p>}
<p>Age: {age}</p>
</div>
);
};
In this example, the `age` and `gender` props are optional, with default values of 18 and undefined respectively. The `greeting` prop is required and has no default value.
By following these best practices, we can ensure that our React components using the FC type are type-safe and less prone to errors, while taking advantage of TypeScript’s strong type system.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律