当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript react.useCallback函数代码示例

本文整理汇总了TypeScript中react.useCallback函数的典型用法代码示例。如果您正苦于以下问题:TypeScript useCallback函数的具体用法?TypeScript useCallback怎么用?TypeScript useCallback使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了useCallback函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: default

export default () => {
  const handleContextMenu = React.useCallback((evt: MouseEvent) => {
    // allow native context menu if it is an input element
    if (evt.target instanceof HTMLInputElement) {
      return
    }

    // disable native context menu
    evt.preventDefault()
  }, [])
  useEventListener(document, 'contextmenu', handleContextMenu)

  const handleKeyDown = React.useCallback((evt: KeyboardEvent) => {
    const isFocusedOnInputWithoutValue =
      document.activeElement instanceof HTMLInputElement && document.activeElement.value === ''
    if (evt.key === 'Escape' && isFocusedOnInputWithoutValue) {
      window.close()
    }
  }, [])
  useEventListener(document, 'keydown', handleKeyDown)

  const handleMouseDown = React.useCallback((evt: MouseEvent) => {
    // disable the scrolling arrows after middle click
    if (evt.button === 1) evt.preventDefault()
  }, [])
  useEventListener(document, 'mousedown', handleMouseDown)
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:27,代码来源:useGlobalEvents.ts

示例2: catch

export function useSessionStorage<T>(key: string, initialValue: T) {
  const [keyValue, setKeyValue] = useState<T>(() => {
    try {
      let value = window.sessionStorage.getItem(key);
      return value !== null ? JSON.parse(value) : initialValue;
    } catch (error) {
      // Return default value if JSON parsing fails
      return initialValue;
    }
  });

  // Wrap in useCallback so the wrapped function is reused
  const setValue = useCallback(
    (value: T) => {
      try {
        window.sessionStorage.setItem(key, JSON.stringify(value));
      } catch (e) {
        // TODO: What should we do here?
        // Example: quota limit reached
      }
      setKeyValue(value);
    },
    [setKeyValue]
  );

  return [keyValue, setValue];
}
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:27,代码来源:useSessionStorage.ts

示例3: useState

function useAsync<Result>(fn: () => Promise<Result>) {
  const [isLoading, setIsLoading] = useState(false);
  const [result, setResult] = useState<Result | null>(null);
  const [err, setError] = useState(null);
  const isMounted = useIsMounted();

  const run = useCallback(async () => {
    setIsLoading(true);

    try {
      const res = await fn();

      if (isMounted.current) {
        setResult(res);
      }
    } catch (error) {
      if (isMounted.current) {
        setError(error);
      }
    } finally {
      if (isMounted.current) {
        setIsLoading(false);
      }
    }
  }, [fn]);

  return {
    isLoading,
    result,
    error: err,
    run,
  };
}
开发者ID:TF2PickupNET,项目名称:TF2Pickup,代码行数:33,代码来源:use-async.ts

示例4: useComponentSize

export function useComponentSize(ref: React.RefObject<HTMLElement>) {
  let [componentSize, setComponentSize] = useState(getSize(ref.current));

  const handleResize = useCallback(
    function handleResize() {
      if (ref.current) {
        setComponentSize(getSize(ref.current));
      }
    },
    [ref]
  );

  useLayoutEffect(() => {
    if (!ref.current) {
      return;
    }

    if (SUPPORTS_RESIZE_OBSERVER) {
      let resizeObserver = new ResizeObserver(() => handleResize());
      resizeObserver.observe(ref.current);

      return () => {
        resizeObserver.disconnect();
      };
    } else {
      window.addEventListener('resize', handleResize);

      return () => {
        window.removeEventListener('resize', handleResize);
      };
    }
  }, [handleResize, ref]);

  return componentSize;
}
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:35,代码来源:useComponentSize.ts

示例5: async

export default function useResource<T>(
  defaultData: T,
  pendingByDefault: boolean = false
): [Resource<T>, ((promise: Promise<T>) => any), (pending?: boolean) => void] {
  const [state, setState] = React.useState<Resource<T>>({
    data: defaultData,
    error: null,
    fulfilled: false,
    pending: pendingByDefault
  });

  const setData = React.useCallback(
    async (promise: Promise<T>) => {
      setState({
        ...state,
        error: null,
        fulfilled: false,
        pending: true
      });
      try {
        setState({
          ...state,
          data: await promise,
          fulfilled: true,
          pending: false
        });
      } catch (e) {
        setState({
          ...state,
          data: defaultData,
          error: e.message,
          pending: false
        });
      }
    },
    [state]
  );

  const markPending = React.useCallback(
    (pending = true) => {
      setState({ ...state, pending });
    },
    [state]
  );

  return [state, setData, markPending];
}
开发者ID:Kanttiinit,项目名称:kanttiinit-web,代码行数:47,代码来源:useResource.ts

示例6: useHistory

export const useUrlState = <State>({
  defaultState,
  decodeUrlState,
  encodeUrlState,
  urlStateKey,
}: {
  defaultState: State;
  decodeUrlState: (value: RisonValue | undefined) => State | undefined;
  encodeUrlState: (value: State) => RisonValue | undefined;
  urlStateKey: string;
}) => {
  const history = useHistory();

  const urlStateString = useMemo(
    () => {
      if (!history) {
        return;
      }

      return getParamFromQueryString(getQueryStringFromLocation(history.location), urlStateKey);
    },
    [history && history.location, urlStateKey]
  );

  const decodedState = useMemo(() => decodeUrlState(decodeRisonUrlState(urlStateString)), [
    decodeUrlState,
    urlStateString,
  ]);

  const state = useMemo(() => (typeof decodedState !== 'undefined' ? decodedState : defaultState), [
    defaultState,
    decodedState,
  ]);

  const setState = useCallback(
    (newState: State | undefined) => {
      if (!history) {
        return;
      }

      const location = history.location;

      const newLocation = replaceQueryStringInLocation(
        location,
        replaceStateKeyInQueryString(
          urlStateKey,
          typeof newState !== 'undefined' ? encodeUrlState(newState) : undefined
        )(getQueryStringFromLocation(location))
      );

      if (newLocation !== location) {
        history.replace(newLocation);
      }
    },
    [encodeUrlState, history, history && history.location, urlStateKey]
  );

  return [state, setState] as [typeof state, typeof setState];
};
开发者ID:elastic,项目名称:kibana,代码行数:59,代码来源:use_url_state.ts

示例7: clearInterval

const useDragAndDropContainerEvents = ({margin = 20}: {margin?: number} = {}) => {
  const {activeKey} = React.useContext(DragAndDropContext)
  const isDragging = activeKey !== null

  const scrollingTimeoutRef = React.useRef<NodeJS.Timeout>()

  const clearScroll = React.useCallback(() => {
    if (scrollingTimeoutRef.current !== undefined) {
      clearInterval(scrollingTimeoutRef.current)
      scrollingTimeoutRef.current = undefined
    }
  }, [])

  React.useEffect(() => {
    if (!isDragging) {
      clearScroll()
    }
  }, [clearScroll, isDragging])

  return React.useMemo(() => {
    const scroll = (containerElement: HTMLElement, {isUpward}: {isUpward: boolean}) => {
      clearScroll()

      scrollingTimeoutRef.current = setInterval(() => {
        containerElement.scrollTo({
          top: containerElement.scrollTop + (isUpward ? -1 : 1) * 20
        })
      }, 50)
    }

    const onMouseMove = (evt: MouseEvent | React.MouseEvent) => {
      if (!isDragging) return

      if (evt.currentTarget instanceof HTMLElement) {
        const rect = evt.currentTarget.getBoundingClientRect()

        const displacementTop = Math.abs(rect.top - evt.clientY)
        const displacementBottom = Math.abs(rect.bottom - evt.clientY)

        if (displacementTop <= margin) {
          scroll(evt.currentTarget, {
            isUpward: true
          })
        } else if (displacementBottom <= margin) {
          scroll(evt.currentTarget, {
            isUpward: false
          })
        } else {
          clearScroll()
        }
      }
    }

    return {
      onMouseMove
    }
  }, [clearScroll, isDragging, margin])
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:58,代码来源:useDragAndDropContainerEvents.ts

示例8: setBodySizeStack

const useBodySizeStack = (): {
  globalBodySize?: BodySize
  appendBodySize: (state: BodySize) => void
  removeBodySize: (state: BodySize) => void
} => {
  const {bodySizeStack, setBodySizeStack} = React.useContext(AbsolutePositionContext)

  const globalBodySize = React.useMemo(() => {
    return bodySizeStack.reduce(
      (acc, bodySize) => {
        return {
          height: bodySize.height ? Math.max(bodySize.height, acc.height || 0) : acc.height,
          width: bodySize.width ? Math.max(bodySize.width, acc.width || 0) : acc.width
        }
      },
      {
        height: undefined,
        width: undefined
      }
    )
  }, [bodySizeStack])

  const appendBodySize = React.useCallback(
    (newBodySize: BodySize) => {
      setBodySizeStack((prevBodySize) => [...prevBodySize, newBodySize])
    },
    [setBodySizeStack]
  )

  const removeBodySize = React.useCallback(
    (oldBodySize: BodySize) => {
      setBodySizeStack((prevBodySize) => {
        return prevBodySize.filter((state) => state !== oldBodySize)
      })
    },
    [setBodySizeStack]
  )

  return {
    globalBodySize,
    appendBodySize,
    removeBodySize
  }
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:44,代码来源:useGlobalBodySize.ts

示例9: dispatch

const useMapDispatchToCallback = <T, U extends Array<V>, V>(
  dispatch: React.Dispatch<T>,
  creator: (...args: U) => T
) => {
  return React.useCallback(
    (...args: U) => {
      dispatch(creator(...args))
    },
    [creator, dispatch]
  )
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:11,代码来源:useMapDispatchToCallback.ts

示例10: useHashScrolling

export function useHashScrolling() {
    const offset = useScrollOffset();
    const calcedOffset = offset.getCalcedHashOffset();
    const callback = useCallback(() => {
        return initHashScrolling(calcedOffset, () => offset.temporarilyDisabledWatching(500));
    }, [calcedOffset]);

    useEffect(() => {
        callback();
    }, [callback]);
}
开发者ID:vanilla,项目名称:vanilla,代码行数:11,代码来源:hashScrolling.ts


注:本文中的react.useCallback函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。