Blame view

天文台pc/tianwentai-ui/node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs 1.41 KB
bc518174   王天杨   提交两个项目文件
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  // packages/react/use-controllable-state/src/useControllableState.tsx
  import * as React from "react";
  import { useCallbackRef } from "@radix-ui/react-use-callback-ref";
  function useControllableState({
    prop,
    defaultProp,
    onChange = () => {
    }
  }) {
    const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });
    const isControlled = prop !== void 0;
    const value = isControlled ? prop : uncontrolledProp;
    const handleChange = useCallbackRef(onChange);
    const setValue = React.useCallback(
      (nextValue) => {
        if (isControlled) {
          const setter = nextValue;
          const value2 = typeof nextValue === "function" ? setter(prop) : nextValue;
          if (value2 !== prop) handleChange(value2);
        } else {
          setUncontrolledProp(nextValue);
        }
      },
      [isControlled, prop, setUncontrolledProp, handleChange]
    );
    return [value, setValue];
  }
  function useUncontrolledState({
    defaultProp,
    onChange
  }) {
    const uncontrolledState = React.useState(defaultProp);
    const [value] = uncontrolledState;
    const prevValueRef = React.useRef(value);
    const handleChange = useCallbackRef(onChange);
    React.useEffect(() => {
      if (prevValueRef.current !== value) {
        handleChange(value);
        prevValueRef.current = value;
      }
    }, [value, prevValueRef, handleChange]);
    return uncontrolledState;
  }
  export {
    useControllableState
  };
  //# sourceMappingURL=index.mjs.map