React hooks 是特殊的函数,允许您在功能组件中使用 React 功能,例如状态和生命周期方法。它们是在 React 16.8 中引入的,目的是简化组件模型,并使跨组件共享状态逻辑变得更容易。
状态管理: 像 useState 这样的钩子允许您在功能组件中添加和管理状态,而不需要将它们转换为类组件。
副作用: useEffect 钩子允许您执行副作用,例如数据获取、订阅或手动更改 DOM,类似于类组件中的生命周期方法。
可重用性:自定义挂钩允许您跨不同组件封装和重用有状态逻辑。
更简洁的代码: 挂钩有助于保持组件
1 useState
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
2 useEffect
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
3 useContext
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div className={`theme-${theme}`}>Current theme: {theme}</div>; };
4 使用Reducer
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
5 useMemo
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
6 useCallback
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onClick={onClick}>{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <Button onClick={increment}>Increment</Button> </div> ); };
7 useRef
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); };
8 useLayoutEffect
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref={divRef}>This is a div</div>; };
9 使用ImperativeHandle
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
10 useDebugValue
- 描述: 在 React DevTools 中显示自定义挂钩的标签,以便于调试。
- 示例:
import React, { useEffect, useState } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(setData); }, []); return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>; };
11 useFetch
- 描述: 用于从 API 获取数据的自定义挂钩。
- 示例:
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div className={`theme-${theme}`}>Current theme: {theme}</div>; };
12 使用本地存储
- 描述: 将状态与本地存储同步以跨会话保存数据。
- 示例:
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
13 使用上一个
- 描述:返回状态或道具的先前值。
- 示例:
import React, { useMemo, useState } from 'react'; const ExpensiveComputation = ({ number }) => { const compute = (num) => { return num * 1000; // Simulate an expensive computation }; const result = useMemo(() => compute(number), [number]); return <div>Computed Result: {result}</div>; };
14 使用Debounce
- 描述:对值或函数调用进行反跳,延迟执行直到指定的延迟之后。
- 示例:
import React, { useCallback, useState } from 'react'; const Button = React.memo(({ onClick, children }) => { console.log('Button rendered'); return <button onClick={onClick}>{children}</button>; }); const App = () => { const [count, setCount] = useState(0); const increment = useCallback(() => setCount(c => c + 1), []); return ( <div> <p>Count: {count}</p> <Button onClick={increment}>Increment</Button> </div> ); };
15 useOnClickOutside
- 描述: 检测指定元素外部的点击,对于关闭弹出窗口或下拉菜单很有用。
- 示例:
import React, { useRef } from 'react'; const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); };
16 使用间隔
- 描述: 设置一个时间间隔,以指定的时间间隔重复运行某个函数。
- 示例:
import React, { useLayoutEffect, useRef } from 'react'; const LayoutEffectExample = () => { const divRef = useRef(); useLayoutEffect(() => { console.log('Height:', divRef.current.clientHeight); }, []); return <div ref={divRef}>This is a div</div>; };
17 useTimeout
- 描述: 设置超时以在指定的延迟后执行函数。
- 示例:
import React, { useImperativeHandle, forwardRef, useRef } from 'react'; const CustomInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} type="text" />; }); const Parent = () => { const ref = useRef(); return ( <div> <CustomInput ref={ref} /> <button onClick={() => ref.current.focus()}>Focus Input</button> </div> ); };
18 useMediaQuery
- 描述: 检查媒体查询是否匹配,从而实现响应式设计逻辑。
- 示例:
import { useDebugValue } from 'react'; const useCustomHook = (value) => { useDebugValue(value ? 'Value is true' : 'Value is false'); return value; }; const DebugExample = () => { const isTrue = useCustomHook(true); return <div>Check the React DevTools</div>; };
19 使用ScrollPosition
- 描述:跟踪窗口的当前滚动位置。
- 示例:
import { useState, useEffect } from 'react'; const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchData = async () => { const response = await fetch(url); const result = await response.json(); setData(result); setLoading(false); }; fetchData(); }, [url]); return { data, loading }; };
20 使用按键
- 描述:检测是否按下特定键。
- 示例:
import { useState, useEffect } from 'react'; const useLocalStorage = (key, initialValue) => { const [storedValue, setStoredValue] = useState(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { console.error(error); return initialValue; } }); useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue)); } catch (error) { console.error(error); } }, [key, storedValue]); return [storedValue, setStoredValue]; };
此列表现在包含每个钩子的描述,让您更清楚地了解其用途和用例。如果您需要更多详细信息或示例,请随时询问!
以上是提升你的 React 技能:理解和使用 Hooks的详细内容。更多信息请关注PHP中文网其他相关文章!