Blame view

天文台pc/tianwentai-ui/node_modules/react-day-picker/src/hooks/useControlledValue/useControlledValue.ts 806 Bytes
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
  import { Dispatch, SetStateAction, useState } from 'react';
  
  export type DispatchStateAction<T> = Dispatch<SetStateAction<T>>;
  
  /**
   * Helper hook for using controlled/uncontrolled values from a component props.
   *
   * When the value is not controlled, pass `undefined` as `controlledValue` and
   * use the returned setter to update it.
   *
   * When the value is controlled, pass the controlled value as second
   * argument, which will be always returned as `value`.
   */
  export function useControlledValue<T>(
    defaultValue: T,
    controlledValue: T | undefined
  ): [T, DispatchStateAction<T>] {
    const [uncontrolledValue, setValue] = useState(defaultValue);
  
    const value =
      controlledValue === undefined ? uncontrolledValue : controlledValue;
  
    return [value, setValue] as [T, DispatchStateAction<T>];
  }