• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript react.useRef函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: addEventListener

const useKeyBindingsEvent = (
  {key, priority, windowId}: KeyBindingMeta,
  callback?: (evt: KeyboardEvent) => void
) => {
  const {addEventListener, removeEventListener} = React.useContext(KeyBindingsContext)

  const callbackRef = React.useRef(callback)
  callbackRef.current = callback

  // use ref as `key` may be a RegExp instance and passing new reference every time
  // it made a trade-off, updating key now doesn't rerun addEventListener/removeEventListener
  const keyRef = React.useRef(key)
  keyRef.current = key

  React.useEffect(() => {
    const meta = {key: keyRef.current, priority, windowId}

    const wrappedCallback = (evt: KeyboardEvent) => {
      if (callbackRef.current) {
        callbackRef.current(evt)
      }
    }

    addEventListener(meta, wrappedCallback)

    return () => {
      removeEventListener(meta, wrappedCallback)
    }
  }, [addEventListener, priority, removeEventListener, windowId])
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:30,代码来源:useKeyBindingsEvent.ts


示例2: useEffect

export function usePrevious<T>(value: T) {
  const ref: React.MutableRefObject<T | null> = useRef<T>(null);
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:7,代码来源:usePrevious.ts


示例3: useReadClassState

export function useReadClassState(
  fixture: React.ReactNode,
  decoratorId: FixtureDecoratorId,
  elRefs: React.MutableRefObject<ElRefs>
) {
  const elPaths = findRelevantElementPaths(fixture);
  const { fixtureState, setFixtureState } = React.useContext(FixtureContext);
  const timeoutId = React.useRef<null | number>(null);

  React.useEffect(() => {
    // The check should run even if no element paths are found at mount, because
    // the fixture can change during the lifecycle of a FixtureCapture instance
    // and the updated fixture might contain elements of stateful components
    scheduleStateCheck();
    return () => {
      if (timeoutId.current) {
        clearTimeout(timeoutId.current);
      }
    };
  });

  function scheduleStateCheck() {
    // Is there a better way to listen to component state changes?
    timeoutId.current = window.setTimeout(checkState, REFRESH_INTERVAL);
  }

  function checkState() {
    let fixtureStateChangeScheduled = false;
    Object.keys(elRefs.current).map(async elPath => {
      if (elPaths.indexOf(elPath) === -1) {
        throw new Error(
          `[FixtureCapture] Child ref exists for missing element path "${elPath}"`
        );
      }

      const { state } = elRefs.current[elPath];
      const elementId = { decoratorId, elPath };
      const fsClassState = findFixtureStateClassState(fixtureState, elementId);
      if (
        fsClassState &&
        state &&
        !doesFixtureStateMatchClassState(fsClassState, state)
      ) {
        fixtureStateChangeScheduled = true;
        setFixtureState(prevFs => ({
          ...prevFs,
          classState: updateFixtureStateClassState({
            fixtureState: prevFs,
            elementId,
            values: createValues(state)
          })
        }));
      }
    });

    if (!fixtureStateChangeScheduled) {
      scheduleStateCheck();
    }
  }
}
开发者ID:skidding,项目名称:cosmos,代码行数:60,代码来源:useReadClassState.ts


示例4: useRef

export function useRefObject<T>(input: T): RefObject<T> {
	const ref = useRef(input)
	useEffect(() => {
		ref.current = input
	}, [input])
	return ref
}
开发者ID:gaearon,项目名称:react-dnd,代码行数:7,代码来源:useRefObject.ts


示例5: useState

export const useQuery = (value: string): Output => {
  const [result, setResult] = useState<Result>([]);
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const debounce = useRef<any>(null);

  useEffect(() => {
    worker.load().then(() => {
      setLoaded(true);
    });
  }, []);

  useEffect(
    () => {
      if (!value) return;

      if (debounce.current) {
        clearTimeout(debounce.current);
      }

      setLoading(true);

      debounce.current = setTimeout(() => {
        worker.solve(value).then((data: any) => {
          setResult(data);
          setLoading(false);
        });
      }, 140);
    },
    [value],
  );

  return { loaded, loading, data: result };
};
开发者ID:kerlends,项目名称:word-solver,代码行数:34,代码来源:useQuery.ts


示例6: Portal

function Portal ({ target, children }: Props) {
  const domStore = useRef<Element>(null)
  if (!domStore.current) {
    domStore.current = document.getElementById(target)
  }
  return createPortal(children, domStore.current)
}
开发者ID:DanSnow,项目名称:react-reversi,代码行数:7,代码来源:Portal.ts


示例7: useFixtureStateRef

// Make latest fixture state accessible in ref callback
function useFixtureStateRef(fixtureState: FixtureState) {
  const ref = React.useRef(fixtureState);
  React.useEffect(() => {
    ref.current = fixtureState;
  });
  return ref;
}
开发者ID:skidding,项目名称:cosmos,代码行数:8,代码来源:useFixtureState.ts


示例8: useRef

export function useDrop<
	DragObject extends DragObjectWithType,
	DropResult,
	CollectedProps
>(
	spec: DropTargetHookSpec<DragObject, DropResult, CollectedProps>,
): [CollectedProps, ConnectDropTarget] {
	const specRef = useRef(spec)
	invariant(spec.accept != null, 'accept must be defined')

	const [monitor, connector] = useDropTargetMonitor()
	useDropHandler(specRef, monitor, connector)

	const result: CollectedProps = useMonitorOutput(
		monitor,
		specRef.current.collect || (() => ({} as CollectedProps)),
		() => connector.reconnect(),
	)

	const connectDropTarget = useMemo(() => connector.hooks.dropTarget(), [
		connector,
	])

	useEffect(() => {
		connector.dropTargetOptions = spec.options || null
		connector.reconnect()
	}, [spec.options])
	return [result, connectDropTarget]
}
开发者ID:gaearon,项目名称:react-dnd,代码行数:29,代码来源:useDrop.ts


示例9: useMemo

export const useSubscription = <T, TVariables = OperationVariables>(
  query: DocumentNode,
  options: SubscriptionOptions<T, TVariables> = {},
): {
  data: T | { [key: string]: void }
  error?: GraphQLError
  loading: boolean
} => {
  const onSubscriptionData = options.onSubscriptionData
  const prevOptions = useRef<typeof options | null>(null)
  const client = useApolloClient()
  const [data, setData] = useState<T | {}>({})
  const [error, setError] = useState<GraphQLError | null>(null)
  const [loading, setLoading] = useState<boolean>(true)

  const subscriptionOptions = {
    query,
    variables: options.variables,
    fetchPolicy: options.fetchPolicy,
  }

  useEffect(
    () => {
      prevOptions.current = subscriptionOptions
      const subscription = client
        .subscribe<{ data: T }, TVariables>(subscriptionOptions)
        .subscribe({
          next: ({ data }) => {
            setData(data)

            if (onSubscriptionData) {
              onSubscriptionData({ client, subscriptionData: data })
            }
          },
          error: err => {
            setError(err)
            setLoading(false)
          },
          complete: () => {
            setLoading(false)
          },
        })

      return () => {
        subscription.unsubscribe()
      }
    },
    [isEqual(prevOptions.current, subscriptionOptions) ? prevOptions.current : subscriptionOptions],
  )

  return useMemo(
    () => ({
      data,
      error,
      loading,
    }),
    [data, error, loading],
  )
}
开发者ID:,项目名称:,代码行数:59,代码来源:


示例10: 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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript react.useState函数代码示例发布时间:2022-05-25
下一篇:
TypeScript react.useReducer函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap