React.FC和React.Component区别

React.FC

全称 React.FunctionComponent,函数组件的类型,表示一个接收 Props 并返回 ReactElement | null 的函数。适合纯 UI 函数组件,不含类组件生命周期/实例成员。

1
2
3
4
5
6
// Props参数在函数组件中可修改
type Props = { title: string };

const MyBtn: React.FC<Props> = ({ title, children }) => {
  return <button>{title}{children}</button>;
};

React.Component<P, S>

React.Component<P, S> 是类组件基类。支持生命周期方法和实例成员,适用于需要类式 API 的场景或旧代码。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/*
Props: 由外部父组件传入,只读。
State: 组件内部自有,可修改,应通过受控方式(setState / setter)更新以保证一致性与正确渲染。

不能写反 React.Component<State, Props>,否则this.props获取到的是state
*/
interface Props { title: string }
interface State { open: boolean }

class Modal extends React.Component<Props, State> {
  state = { open: false };
  componentDidMount() { /*...*/ }
  render() { return <div>{this.props.title}</div>; }
}

interface和type区别

  • 含义:interface 用于声明对象/类的形状;type 更通用,可表示对象、联合、交叉、原始类型等。

  • 可扩展性:interface 支持声明合并(同名 interface 会合并);type 不支持声明合并。

  • 继承/组合:interface 用 extends 继承多个接口;type 用交叉 & 组合类型,功能等价但语法不同。

  • 联合/交叉与映射类型:type 能直接定义联合(A | B)、交叉(A & B)与映射类型({ [K in Keys]: … });interface 不能直接表示联合类型。

  • 可读性与错误信息:interface 在面向对象风格和 API 设计上更清晰,TypeScript 的错误信息对 interface 往往更友好。

  • 何时用:如果需要声明库 API、面向 OOP 或需声明合并用 interface;若需联合类型、交叉类型或别名(包括原始、元组等)用 type。

comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计