您好,登录后才能下订单哦!
React Hooks 是 React 16.8 版本引入的一个新特性,它允许你在不编写类(class)的情况下使用 state 和其他 React 特性。Hooks 是一些可以让你在函数组件里“钩入” React state 及生命周期等特性的函数。以下是一些常用的 Hooks 及其用法:
useState
是一个让函数组件可以使用 state 的 Hook。
import React, { useState } from 'react';
function Example() {
// 声明一个新的 state 变量,我们将其称为 "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
是一个让你在函数组件中执行副作用操作的 Hook。
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// 类似于 componentDidMount 和 componentDidUpdate:
useEffect(() => {
// 使用浏览器的 API 更新页面标题
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。
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function Example() {
const theme = useContext(ThemeContext);
return <div theme={theme}>...</div>;
}
useReducer
是另一种可以在 React 组件中管理复杂 state 的 Hook。
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, {count: 0});
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
useCallback
返回一个记忆化的回调函数。
import React, { useCallback, useState } from 'react';
function Example({ someProp }) {
const [count, setCount] = useState(0);
const memoizedCallback = useCallback(
() => {
doSomething(count, someProp);
},
[count, someProp], // 依赖列表
);
return <ChildComponent onIncrement={memoizedCallback} />;
}
useMemo
返回一个记忆化的值。
import React, { useMemo, useState } from 'react';
function Example({ list }) {
const [filter, setFilter] = useState('');
const filteredList = useMemo(() => {
return list.filter(item => item.includes(filter));
}, [list, filter]);
return (
<div>
<input value={filter} onChange={e => setFilter(e.target.value)} />
{filteredList.map(item => <div key={item}>{item}</div>)}
</div>
);
}
useRef
返回一个可变的 ref 对象,其 .current
属性被初始化为传入的参数(initialValue)。返回的对象在组件的整个生命周期内持续存在。
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` 指向已挂载到 DOM 上的文本输入元素
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
你还可以创建自己的 Hooks 来复用组件逻辑。
import { useState, useEffect } from 'react';
function useCustomHook() {
const [data, setData] = useState(null);
useEffect(() => {
// 获取数据的逻辑...
fetchData().then(fetchedData => setData(fetchedData));
}, []); // 空依赖数组意味着这个 effect 只会在组件挂载时运行一次
return data;
}
function MyComponent() {
const data = useCustomHook();
// 使用 data...
}
这些是 React Hooks 的一些基本用法。Hooks 提供了一种更直观的方式来使用 React 的特性,而且它们可以帮助你更好地组织和管理组件逻辑。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。