React Hooks
React Hooks 允许您在无需编写 class 组件的情况下,在函数组件中使用状态 state 、副作用 effect 等特性。Hooks 提供了更简洁易理解方式来编写组件。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>当前计数:{count}</p>
{/* 点击按钮时,调用 setCount 更新 count */}
<button onClick={() => setCount(count + 1)}>增加</button>
</div>
);
}
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
import React, { useContext } from 'react';
const ThemeContext = React.createContext();
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ backgroundColor: theme.background, color: theme.foreground }}>
Themed Button
</button>
);
}
function App() {
const theme = { background: 'blue', foreground: 'white' };
return (
<ThemeContext.Provider value={theme}>
<ThemedButton />
</ThemeContext.Provider>
);
}
import React, { useRef } from 'react';
function FocusableInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} />;
}
import React, { useMemo, useState } from 'react';
function ExpensiveCalculation({ data }) {
const result = useMemo(() => {
return data * 2;
}, [data]);
return <p>计算结果: {result}</p>;
}
import React, { useCallback, useState } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>计数:{count}</p>
<ChildComponent onClick={handleClick} />
</div>
);
}
function ChildComponent({ onClick }) {
return <button onClick={onClick}>增加</button>;
}
以上是 React Hooks 中的一些示例用法 useState 、 useEffect 、 useContext 、 useRef 、 useMemo , useCallback 等常用的 Hooks。