react如何使用函数
函数组件的基本用法
在React中,函数组件是通过JavaScript函数定义的组件,接收props作为参数并返回React元素。
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
使用Hooks扩展功能
React Hooks允许函数组件管理状态和其他特性。常用Hooks包括:
-
useState:管理组件内部状态。
import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); } -
useEffect:处理副作用(如数据获取、订阅)。import { useEffect } from 'react'; function DataFetcher() { useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()); }, []); // 空依赖数组表示仅在挂载时执行 }
传递Props
函数组件通过props接收父组件传递的数据:

function UserCard({ name, age }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
// 使用方式
<UserCard name="Alice" age={25} />
自定义Hook复用逻辑
将共享逻辑提取为自定义Hook(命名以use开头):
function useToggle(initialValue = false) {
const [value, setValue] = useState(initialValue);
const toggle = () => setValue(!value);
return [value, toggle];
}
// 使用示例
function ToggleButton() {
const [isOn, toggleIsOn] = useToggle();
return <button onClick={toggleIsOn}>{isOn ? 'ON' : 'OFF'}</button>;
}
性能优化
-
React.memo:避免不必要的重新渲染。const MemoizedComponent = React.memo(function MyComponent(props) { /* 仅在props变化时重新渲染 */ }); -
useCallback/useMemo:缓存函数或计算结果。const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]); // 依赖变化时重新创建






