Blame view

天文台pc/tianwentai-ui/node_modules/use-callback-ref/dist/es5/useRef.js 1.33 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
  "use strict";
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.useCallbackRef = void 0;
  var react_1 = require("react");
  /**
   * creates a MutableRef with ref change callback
   * @param initialValue - initial ref value
   * @param {Function} callback - a callback to run when value changes
   *
   * @example
   * const ref = useCallbackRef(0, (newValue, oldValue) => console.log(oldValue, '->', newValue);
   * ref.current = 1;
   * // prints 0 -> 1
   *
   * @see https://reactjs.org/docs/hooks-reference.html#useref
   * @see https://github.com/theKashey/use-callback-ref#usecallbackref---to-replace-reactuseref
   * @returns {MutableRefObject}
   */
  function useCallbackRef(initialValue, callback) {
      var ref = (0, react_1.useState)(function () { return ({
          // value
          value: initialValue,
          // last callback
          callback: callback,
          // "memoized" public interface
          facade: {
              get current() {
                  return ref.value;
              },
              set current(value) {
                  var last = ref.value;
                  if (last !== value) {
                      ref.value = value;
                      ref.callback(value, last);
                  }
              },
          },
      }); })[0];
      // update callback
      ref.callback = callback;
      return ref.facade;
  }
  exports.useCallbackRef = useCallbackRef;