Files
workspace/code/allapp/allapp-rn/src/hooks/useKeyboardHeight.ts
T
2026-01-13 22:18:01 +08:00

32 lines
810 B
TypeScript

import type { KeyboardEvent } from 'react-native'
import { useEffect, useState } from 'react'
import { Keyboard } from 'react-native'
/**
* useKeyboardHeight - 获取键盘高度的 Hooks
* @returns {number} 当前键盘高度,键盘收起时为 0
*/
export function useKeyboardHeight() {
const [keyboardHeight, setKeyboardHeight] = useState(0)
useEffect(() => {
const onKeyboardShow = (e: KeyboardEvent) => {
setKeyboardHeight(e.endCoordinates.height)
}
const onKeyboardHide = () => {
setKeyboardHeight(0)
}
const showSub = Keyboard.addListener('keyboardDidShow', onKeyboardShow)
const hideSub = Keyboard.addListener('keyboardDidHide', onKeyboardHide)
return () => {
showSub.remove()
hideSub.remove()
}
}, [])
return keyboardHeight
}