React.FC介绍

React.FC是React中的一种函数组件类型,是在TypeScript中使用的一个泛型,FC即Function Component的缩写,表示一个接收props作为输入并返回JSX元素的函数组件。

使用React.FC可以为组件定义类型,提供props的类型作为泛型参数,享受TypeScript的类型检查和自动补全等特性。同时,React.FC也明确了组件的返回类型,其返回类型被限定为React元素(JSX.Element)或null。

下面是一个简单的例子:

复制代码
import React from 'react';  
  
interface MyProps {  
  name: string;  
  age: number;  
}  
  
const MyComponent: React.FC<MyProps> = ({ name, age }) => {  
  return (  
    <div>  
      <h1>Hello, {name}!</h1>  
      <p>You are {age} years old.</p>  
    </div>  
  );  
};  
  
export default MyComponent;

在这个例子中,我们定义了一个名为 MyComponent 的函数组件,它接受一个 MyProps 类型的 props。MyProps 接口定义了 name 和 age 两个属性,它们的类型分别是 string 和 number。

与React.Component(类组件)相比,React.FC(函数式组件)是一个纯函数,不能使用setState,而是使用useState()、useEffect等Hook API。函数式组件也称为无状态组件,它包含了PropsWithChildren的泛型,不需要显式地声明props.children的类型。

简单实现页面数字1秒后加1:

复制代码
import React, { useState, useEffect } from 'react';  
 
const App: React.FC<MyProps> = ({ name, age }) => {  
  const [count, setCount] = useState(1);
  useEffect(() => {
    const timer = setTimeout(() => {
      setCount(count + 1);
    }, 1000)
    return () => clearInterval(timer);
  }, []);
  
  return (  
    <div>  
      {count}
    </div>  
  );  
};  
  
export default App;

useEffect相当于componentDidMount、componentDidUpdate和componentWillUnmount的组合体,可以在函数组建中替代生命周期。

1.传递一个空数组作为第二个参数,这个 Effect 将永远不会重复执行,可以替代componentDidMount。

复制代码
useEffect(() => {
  console.log('componentDidMount');
}, []);

2.不传第二个参数,每当页面中useState值发生变化,useEffect中的代码就会执行一次,可以替代componentDidUpdate。

复制代码
useEffect(() => {
  console.log('componentDidUpdate');
});

3.useEffect可以返回一个函数,该函数将在组件被卸载时的执行,可以替代componentWillUnmount。

复制代码
useEffect(() => {
  return () => {
  	console.log('componentWillUnmount');
  };
});
相关推荐
passerby606143 分钟前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte3 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc