Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 60x 932x 932x 476x 456x 6x 6x 6x | import { useState } from "react"; const noop = () => {}; export interface ChangeHandler<T, P extends any[]> { (value: T, ...args: P); } export function useDefault<T, P extends any[]>( value: T, defaultValue: T, onChange: ChangeHandler<T, P> ): [T, ChangeHandler<T, P>] { // 无论是否受控,都要 useState,因为 Hooks 是无条件的 const [internalValue, setInternalValue] = useState(defaultValue); // 受控模式 if (typeof value !== "undefined") { return [value, onChange || noop]; } // 非受控模式 return [ internalValue, (newValue, ...args) => { setInternalValue(newValue); Eif (typeof onChange === "function") { onChange(newValue, ...args); } }, ]; } |