📅  最后修改于: 2023-12-03 15:04:48.505000             🧑  作者: Mango
React Hooks 是 React 的一个特性,它在 React 16.8 版本中引入。它通过一个简单而易于使用的 API,使得你能在 React 函数式组件中使用 state 和其他 React 特性,脱离了使用 class 组件的限制。
使用 React Hooks,你可以:
useState 是 React Hooks 中最常使用的一个。它用于在函数式组件中添加 state,可以理解为类组件的 this.state。useState 函数接收一个初始值,返回一个包含当前 state 和更新 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 用于在函数式组件中添加副作用,可以理解为类组件的 componentDidMount、componentDidUpdate 和 componentWillUnmount。useEffect 接收一个回调函数和一个依赖项数组作为参数。
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 用于在函数式组件中使用 React Context,可以理解为类组件的 this.context。useContext 接收一个 Context 对象作为参数,返回当前 Context 的 value。
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function Example() {
const theme = useContext(ThemeContext);
return (
<div className={`theme-${theme}`}>
<p>Current theme: {theme}</p>
</div>
);
}
useRef 用于在函数式组件中创建一个 ref,可以理解为类组件的 this.refs。useRef 返回一个对象,包含一个名为 current 的属性,其初始值为传入 useRef 的参数。
import React, { useRef } from 'react';
function Example() {
const inputRef = useRef(null);
function handleClick() {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Focus</button>
</div>
);
}
自定义 Hook 可以让你重用一些可复用的逻辑,并使你的代码更加模块化。自定义 Hook 是一个函数,它可以使用其他 React Hooks,如 useState、useEffect 等,并返回一个自定义的 Hook。
import { useState, useEffect } from 'react';
function useWindowScroll() {
const [scrollY, setScrollY] = useState(window.scrollY);
useEffect(() => {
function handleScroll() {
setScrollY(window.scrollY);
}
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return scrollY;
}
以上就是 React Hooks 的一些简单介绍,这只是一个简单的入门,更多内容可以查看 React 官网的 Hooks 文档。