函数组件
这些可以编写为普通的函数,接收一个 `props` 参数并返回一个 JSX 元素。
// Declaring type of props - see "Typing Component Props" for more examples
type AppProps = {
message: string;
}; /* use `interface` if exporting so that consumers can extend */
// Easiest way to declare a Function Component; return type is inferred.
const App = ({ message }: AppProps) => <div>{message}</div>;
// You can choose to annotate the return type so an error is raised if you accidentally return some other type
const App = ({ message }: AppProps): React.JSX.Element => <div>{message}</div>;
// You can also inline the type declaration; eliminates naming the prop types, but looks repetitive
const App = ({ message }: { message: string }) => <div>{message}</div>;
// Alternatively, you can use `React.FunctionComponent` (or `React.FC`), if you prefer.
// With latest React types and TypeScript 5.1. it's mostly a stylistic choice, otherwise discouraged.
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
// or
const App: React.FC<AppProps> = ({ message }) => <div>{message}</div>;
提示:您可以使用 Paul Shen 的 VS Code 扩展来自动化类型解构声明(包括 键盘快捷键)。
为什么不需要 `React.FC`?`React.FunctionComponent` / `React.VoidFunctionComponent` 又是什么?
您可能在许多 React+TypeScript 代码库中看到过这种写法
const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
<div>{message}</div>
);
然而,目前普遍认为不需要使用 `React.FunctionComponent`(或简写 `React.FC`)。如果您仍在使用 React 17 或低于 5.1 的 TypeScript 版本,甚至 不建议使用。当然,这是一种细微的看法,但如果您同意并希望从代码库中删除 `React.FC`,则可以使用 此 jscodeshift 代码修改工具。
与“普通函数”版本的一些区别
`React.FunctionComponent` 明确指定了返回类型,而普通函数版本是隐式的(或者需要额外的注释)。
它为静态属性(如 `displayName`、`propTypes` 和 `defaultProps`)提供类型检查和自动完成。
- 请注意,使用 `React.FunctionComponent` 与 `defaultProps` 存在一些已知问题。有关详细信息,请参阅 此问题。我们维护了一个单独的 `defaultProps` 部分,您也可以查阅。
在 React 18 类型更新 之前,`React.FunctionComponent` 提供了 `children` 的隐式定义(见下文),这引发了激烈的讨论,也是 从 Create React App TypeScript 模板中删除 `React.FC` 的原因之一。
// before React 18 types
const Title: React.FunctionComponent<{ title: string }> = ({
children,
title,
}) => <div title={title}>{children}</div>;
(已弃用)使用 `React.VoidFunctionComponent` 或 `React.VFC` 代替
在 @types/react 16.9.48 中,添加了 `React.VoidFunctionComponent` 或 `React.VFC` 类型以显式地为 `children` 添加类型。但是,请注意,`React.VFC` 和 `React.VoidFunctionComponent` 在 React 18 中已弃用(https://github.com/DefinitelyTyped/DefinitelyTyped/pull/59882),因此此临时解决方案在 React 18 及更高版本中不再必要或推荐。
请改用常规函数组件或 `React.FC`。
type Props = { foo: string };
// OK now, in future, error
const FunctionComponent: React.FunctionComponent<Props> = ({
foo,
children,
}: Props) => {
return (
<div>
{foo} {children}
</div>
); // OK
};
// Error now, in future, deprecated
const VoidFunctionComponent: React.VoidFunctionComponent<Props> = ({
foo,
children,
}) => {
return (
<div>
{foo}
{children}
</div>
);
};
- 将来,它可能会自动将 props 标记为 `readonly`,不过如果 props 对象在参数列表中被解构,那么这一点就变得无关紧要了。
在大多数情况下,使用哪种语法差别不大,但您可能更喜欢 `React.FunctionComponent` 的显式特性。