如何做品牌網(wǎng)站汕頭網(wǎng)站建設技術外包
React.FC是React中的一種函數(shù)組件類型,是在TypeScript中使用的一個泛型,FC即Function Component的縮寫,表示一個接收props作為輸入并返回JSX元素的函數(shù)組件。
使用React.FC可以為組件定義類型,提供props的類型作為泛型參數(shù),享受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 的函數(shù)組件,它接受一個 MyProps 類型的 props。MyProps 接口定義了 name 和 age 兩個屬性,它們的類型分別是 string 和 number。
與React.Component(類組件)相比,React.FC(函數(shù)式組件)是一個純函數(shù),不能使用setState,而是使用useState()、useEffect等Hook API。函數(shù)式組件也稱為無狀態(tài)組件,它包含了PropsWithChildren的泛型,不需要顯式地聲明props.children的類型。
簡單實現(xiàn)頁面數(shù)字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的組合體,可以在函數(shù)組建中替代生命周期。
1.傳遞一個空數(shù)組作為第二個參數(shù),這個 Effect 將永遠不會重復執(zhí)行,可以替代componentDidMount。
useEffect(() => {console.log('componentDidMount');
}, []);
2.不傳第二個參數(shù),每當頁面中useState值發(fā)生變化,useEffect中的代碼就會執(zhí)行一次,可以替代componentDidUpdate。
useEffect(() => {console.log('componentDidUpdate');
});
3.useEffect可以返回一個函數(shù),該函數(shù)將在組件被卸載時的執(zhí)行,可以替代componentWillUnmount。
useEffect(() => {return () => {console.log('componentWillUnmount');};
});