React Native Make View “Hug” the Top of the Keyboard

后端 未结 5 1963
陌清茗
陌清茗 2021-02-13 03:48

Let\'s say I have a view that is positioned absolute at the bottom of the screen. This view contains a text input. When the text input is focused, I want the bottom of the view

5条回答
  •  甜味超标
    2021-02-13 04:11

    Custom hook:

    import { useRef, useEffect } from 'react';
    import { Animated, Keyboard, KeyboardEvent } from 'react-native';
    
    export const useKeyboardHeight = () => {
      const keyboardHeight = useRef(new Animated.Value(0)).current;
    
      useEffect(() => {
        const keyboardWillShow = (e: KeyboardEvent) => {
          Animated.timing(keyboardHeight, {
            duration: e.duration,
            toValue: e.endCoordinates.height,
            useNativeDriver: true,
          }).start();
        };
    
        const keyboardWillHide = (e: KeyboardEvent) => {
          Animated.timing(keyboardHeight, {
            duration: e.duration,
            toValue: 0,
            useNativeDriver: true,
          }).start();
        };
    
        const keyboardWillShowSub = Keyboard.addListener(
          'keyboardWillShow',
          keyboardWillShow
        );
        const keyboardWillHideSub = Keyboard.addListener(
          'keyboardWillHide',
          keyboardWillHide
        );
    
        return () => {
          keyboardWillHideSub.remove();
          keyboardWillShowSub.remove();
        };
      }, [keyboardHeight]);
    
      return keyboardHeight;
    };
    

提交回复
热议问题