React Hooks 是 React 16.8 版本引入的新特性,它允许你在不编写类的情况下使用 state 以及其他的 React 特性。以下是一些关于 React Hooks 的基础教程。
常用 Hooks
useState
useState
是最基础的 Hook,用于在函数组件中添加 state。
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
useEffect
用于在组件渲染后执行副作用操作,类似于类组件中的 componentDidMount
和 componentDidUpdate
。
import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
// 组件挂载后执行的代码
console.log('Component mounted');
return () => {
// 组件卸载前执行的代码
console.log('Component will unmount');
};
}, []); // 空数组表示这个 effect 只在组件挂载和卸载时执行
return <div>Hello, world!</div>;
}
useContext
useContext
用于在组件树中跨多级组件传递数据,而不需要手动添加 props。
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme.bg, color: theme.fg }}>{theme.text}</button>;
}
更多资源
想要了解更多关于 React Hooks 的内容,可以访问我们网站的 React Hooks 教程。
图片
React Hooks