🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ## 自定义 hook 创建自定义 Hook 的几个重要原则: * 命名规则:必须以 "use" 开头 * 组合性:可以在自定义 Hook中使用其他的 Hook * 状态隔离:每个组件调用同一个Hook 时会获得独立的状态 * 参数传递:可以接收参数来自定义行为 * 返回值灵活:可以返回任何值(对象、数组等) ## 示例 ### 自增示例 ``` import { useState, useCallback } from 'react'; interface UseCounterProps { initialValue?: number; step?: number; } const useCounter = ({ initialValue = 0, step = 1 }: UseCounterProps = {}) => { const [count, setCount] = useState(initialValue); const increment = useCallback(() => { setCount(prev => prev + step); }, [step]); const decrement = useCallback(() => { setCount(prev => prev - step); }, [step]); const reset = useCallback(() => { setCount(initialValue); }, [initialValue]); return { count, increment, decrement, reset }; }; export default useCounter; ``` > useCallback 主要用于性能优化,它可以缓存函数引用,避免在组件重新渲染时重复创建函数。 使用 ``` import useCounter from '../hooks/useCounter'; const Counter = () => { const { count, increment, decrement, reset } = useCounter({ initialValue: 0, step: 2 }); return ( <div> <p>当前计数:{count}</p> <button onClick={increment}>增加</button> <button onClick={decrement}>减少</button> <button onClick={reset}>重置</button> </div> ); }; ``` ### 封装localStorage ``` import { useState, useEffect } from 'react'; const useLocalStorage = <T>(key: string, initialValue: T) => { // 获取初始值 const [storedValue, setStoredValue] = useState<T>(() => { try { const item = window.localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } }); // 监听变化并更新 localStorage useEffect(() => { try { window.localStorage.setItem(key, JSON.stringify(storedValue)); } catch (error) { console.error(error); } }, [key, storedValue]); return [storedValue, setStoredValue] as const; }; export default useLocalStorage; ``` ### hook 使用扩展函数 useFormInput.js ``` import { useState } from 'react'; export function useFormInput(initialValue) { const [value, setValue] = useState(initialValue); function handleChange(e) { setValue(e.target.value); } const inputProps = { value: value, onChange: handleChange }; return inputProps; } ``` 使用 ``` import { useFormInput } from './useFormInput.js'; export default function Form() { const firstNameProps = useFormInput('Mary'); const lastNameProps = useFormInput('Poppins'); return ( <> <label> First name: <input {...firstNameProps} /> </label> <label> Last name: <input {...lastNameProps} /> </label> <p><b>Good morning, {firstNameProps.value} {lastNameProps.value}.</b></p> </> ); } ```