當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript react.useContext函數代碼示例

本文整理匯總了TypeScript中react.useContext函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript useContext函數的具體用法?TypeScript useContext怎麽用?TypeScript useContext使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了useContext函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: useField

export default function useField(name: string) {
  const {
    initialData,
    errors,
    scopePath,
    unregisterField,
    registerField
  } = useContext(FormContext);

  const fieldName = scopePath ? `${scopePath}.${name}` : name;

  useEffect(() => {
    return () => unregisterField(fieldName);
  }, []);

  const defaultValue = dot.pick(fieldName, initialData);
  const error = errors[fieldName];

  return {
    fieldName,
    registerField,
    defaultValue,
    error
  };
}
開發者ID:isacmoura,項目名稱:unform,代碼行數:25,代碼來源:useField.ts

示例2: useContext

export const useExit = (error?: Error) => {
  const { exit } = useContext(AppContext);

  useEffect(() => {
    (exit as any)(error);
  }, [exit]);
};
開發者ID:valtech-nyc,項目名稱:brookjs,代碼行數:7,代碼來源:util.ts

示例3: useContext

  ({
    children,
    filterQuery,
    visibleMidpointTime,
  }: {
    children: RendererFunction<{ buckets: LogSummaryBuckets }>;
    filterQuery: string | null;
    visibleMidpointTime: number | null;
  }) => {
    const { intervalSize } = useContext(LogViewConfiguration.Context);
    const { sourceId } = useContext(Source.Context);

    const { buckets } = useLogSummary(sourceId, visibleMidpointTime, intervalSize, filterQuery);

    return children({ buckets });
  }
開發者ID:elastic,項目名稱:kibana,代碼行數:16,代碼來源:with_summary.ts

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

示例5: useLocale

/**
 * Hook that returns a function to translate strings.
 */
export default function useLocale(wildcard: string): tFunc {
	const {curLang, locales} = useContext(LocaleContext);

	function t(str: string | TemplateStringsArray,
			...args: (string | number)[]): string {
		return rawTranslate(curLang, locales, wildcard, str, ...args);
	}

	return t;
}
開發者ID:rodrigocfd,項目名稱:wikipedia-templates,代碼行數:13,代碼來源:useLocale.ts

示例6: useContext

  function useContext() {
    const value = React.useContext(Context)

    if (value === null) {
      throw new Error(
        `${useValue.name} must be used within a ${Provider.displayName}`
      )
    }

    return value
  }
開發者ID:8th713,項目名稱:cockpit-for-pixiv,代碼行數:11,代碼來源:createUseContext.ts

示例7: useContext

export function useStorage<T>(key: string, defaultValue: T) {
  const storage = useContext(StorageContext)
  const [value, set] = useState(() => load(storage, key, defaultValue))

  useEffect(() => {
    store(storage, key, value)
  }, [value])

  useEffect(() => {
    set(load(storage, key, defaultValue))
  }, [key, storage])

  return [value, set] as const
}
開發者ID:8th713,項目名稱:cockpit-for-pixiv,代碼行數:14,代碼來源:useStorage.ts

示例8: useContext

const useNotistack = () => {
	const enqueueSnackbar = useContext(SnackbarContextNext);

	const enqueueSuccess = (message: string) =>
		enqueueSnackbar(message, {
			variant: 'success'
		});

	const enqueueError = (message: string) =>
		enqueueSnackbar(message, {
			variant: 'error'
		});

	return {
		enqueueError,
		enqueueSuccess
	};
};
開發者ID:kvasnyk,項目名稱:CILantro,代碼行數:18,代碼來源:useNotistack.ts

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

示例10: useImg

export function useImg(page: Page) {
  const unmounted = useUnmount()
  const { fetchImage } = useContext(ClientContext)
  const [url, setUrl] = useState(() =>
    page.urls.small.replace('540x540_70', '150x150')
  )

  useEffect(() => {
    if (url === page.urls.original) return

    fetchImage(page.urls.original).then(src => {
      if (unmounted.current) return
      if (src === null) return

      setUrl(src)
    })
  }, [])

  return url
}
開發者ID:8th713,項目名稱:cockpit-for-pixiv,代碼行數:20,代碼來源:useImg.ts


注:本文中的react.useContext函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。