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.

posted @ 2024-04-02 15:10  saaspeter  阅读(107)  评论(0编辑  收藏  举报