这个语法是 TypeScript + React 的组合写法,表示你声明了一个 函数式组件(Function Component),并且给它加上了明确的类型定义。
我们来拆解一下这句代码:
const ChatBox: React.FC = () => ...
✅ 含义逐个解释
片段 | 含义 |
---|---|
const ChatBox | 定义了一个常量组件名字叫 ChatBox |
: React.FC | 使用 TypeScript 类型标注,表示 ChatBox 是一个 React 函数组件(Function Component) |
= () => {} | 组件的具体内容,箭头函数的形式 |
🧠 那 React.FC
是什么?
-
React.FC
是 React 提供的一个 类型别名(Type Alias),全称是React.FunctionComponent
-
它帮你自动加上了:
-
props
的类型检查 -
函数组件默认的返回值(JSX)
-
children 支持(默认有
children
属性)
-
📦 举个例子
import React from 'react';
const ChatBox: React.FC = () => {
return (
<div>
Hello, this is a chat box.
</div>
);
};
export default ChatBox;
💡如果组件有 props 呢?
那你可以传泛型给 React.FC<你的Props类型>
:
type ChatBoxProps = {
username: string;
};
const ChatBox: React.FC<ChatBoxProps> = ({ username }) => {
return <div>Hello, {username}!</div>;
};
🛑 一点提醒
现在社区里有些人建议不要用 React.FC
,而是直接手动写 props 类型,比如:
type ChatBoxProps = {
username: string;
};
const ChatBox = ({ username }: ChatBoxProps) => {
return <div>Hello, {username}!</div>;
};
原因:
-
React.FC
默认加了children
,有时候你不需要 -
泛型推导可能不够灵活
但对于入门或者通用组件,React.FC
依然很好用。