React Hooks 入门指南:从零到实战

什么是 React Hooks?

React Hooks 是 React 16.8 引入的新特性,它让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

基础 Hooks

1. useState

useState 是最常用的 Hook,它允许你在函数组件中添加 state。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>
);
}

2. useEffect

useEffect Hook 让你在函数组件中执行副作用操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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>
);
}

自定义 Hooks

你可以创建自己的 Hooks 来复用状态逻辑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { useState, useEffect } from 'react';

function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);

useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);

return width;
}

// 使用自定义 Hook
function MyComponent() {
const width = useWindowWidth();
return <div>Window width: {width}</div>;
}

最佳实践

  1. 只在最顶层使用 Hooks
  2. 只在 React 函数中调用 Hooks
  3. 自定义 Hook 以 “use” 开头
  4. 使用 eslint-plugin-react-hooks

总结

React Hooks 让函数组件拥有了类组件的能力,使得代码更加简洁、易于复用。掌握 Hooks 是现代 React 开发的必备技能。


相关文章: