react如何使用函数
使用函数组件的基本语法
React 的函数组件是一种通过 JavaScript 函数定义的组件形式。函数组件接收 props 作为参数,并返回 React 元素。
function Greeting(props) {
return <h1>Hello, {props.name}</h1>;
}
使用 Hooks 管理状态
React Hooks 允许在函数组件中使用状态和其他 React 特性。useState 是最常用的 Hook,用于管理局部状态。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
处理副作用
useEffect Hook 用于在函数组件中执行副作用操作,例如数据获取、订阅或手动修改 DOM。

import React, { useState, useEffect } from 'react';
function Example() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data ? <div>{data.message}</div> : <div>Loading...</div>}
</div>
);
}
自定义 Hooks
自定义 Hooks 可以将组件逻辑提取到可重用的函数中。自定义 Hook 是一个以 use 开头的函数,可以调用其他 Hooks。
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, [url]);
return data;
}
function MyComponent() {
const data = useFetch('https://api.example.com/data');
return (
<div>
{data ? <div>{data.message}</div> : <div>Loading...</div>}
</div>
);
}
传递 Props
函数组件通过 props 接收父组件传递的数据。Props 是只读的,不能在子组件中直接修改。

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return <Welcome name="Alice" />;
}
使用 Context
useContext Hook 允许函数组件订阅 React 的 Context 对象,无需通过 Props 层层传递数据。
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Click me</button>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
性能优化
React.memo 可以对函数组件进行浅比较,避免不必要的渲染。useMemo 和 useCallback 可以缓存计算结果和函数引用。
import React, { useMemo, useCallback } from 'react';
const ExpensiveComponent = React.memo(function({ compute, onClick }) {
const result = compute();
return <button onClick={onClick}>Result: {result}</button>;
});
function ParentComponent() {
const [count, setCount] = useState(0);
const compute = useMemo(() => () => count * 2, [count]);
const handleClick = useCallback(() => setCount(count + 1), [count]);
return <ExpensiveComponent compute={compute} onClick={handleClick} />;
}






