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
用于在组件渲染后执行副作用操作,比如数据获取、订阅或者手动更改 DOM。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useContext
useContext
允许你订阅 context 的变化,并重新渲染组件。
import React, { useContext } from 'react';
const ThemeContext = React.createContext();
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
<button style={{ background: theme.background, color: theme.color }}>
Hello World
</button>
);
}
扩展阅读
更多关于 React Hooks 的内容,可以参考 React 官方文档。
React Hooks