网站开发招标技术规范书,创网站多少钱,wordpress 添加备案,知东莞app下载React.FC是React中的一种函数组件类型#xff0c;是在TypeScript中使用的一个泛型#xff0c;FC即Function Component的缩写#xff0c;表示一个接收props作为输入并返回JSX元素的函数组件。 使用React.FC可以为组件定义类型#xff0c;提供props的类型作为泛型参数#x…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.FCMyProps ({ name, age }) { return ( div h1Hello, {name}!/h1 pYou 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.FCMyProps ({ 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);};
});