How to get a height of a Keyboard in React-Native?

后端 未结 4 1073
一整个雨季
一整个雨季 2020-12-08 03:49

I am using React-Navigation in my app and the app consists of StackNavigator with multiple screens, some screens of which have TextInput with autoFocus={true}

4条回答
  •  误落风尘
    2020-12-08 04:51

    I also needed a hook for it, so that is how I get the height of the keyboard (largely inspired by the other answer), the code example is in TypeScript:

    import { useEffect, useState } from 'react';
    import { Keyboard, KeyboardEvent } from 'react-native';
    
    export const useKeyboard = (): [number] => {
      const [keyboardHeight, setKeyboardHeight] = useState(0);
    
      function onKeyboardDidShow(e: KeyboardEvent): void {
        setKeyboardHeight(e.endCoordinates.height);
      }
    
      function onKeyboardDidHide(): void {
        setKeyboardHeight(0);
      }
    
      useEffect(() => {
        Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);
        Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);
        return (): void => {
          Keyboard.removeListener('keyboardDidShow', onKeyboardDidShow);
          Keyboard.removeListener('keyboardDidHide', onKeyboardDidHide);
        };
      }, []);
    
      return [keyboardHeight];
    };
    

    then in your component:

      const [keyboardHeight] = useKeyboard();
      console.log(keyboardHeight);
    

提交回复
热议问题