如何在 React-Native 中获取键盘的高度?

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

我在我的应用程序中使用 React-Navigation,该应用程序由具有多个屏幕的 StackNavigator 组成,其中一些屏幕具有带有 autoFocus={true}

的 TextInput

问题:在这些屏幕上当组件呈现时,屏幕的高度正在构造函数中设置:

constructor(props) {
    super(props);
    this.state = { 
        height: Dimensions.get('window').height,
    };
}

但是,由于 TextInput 的 autoFocustrue,此屏幕上的键盘在渲染后几乎立即弹出,由于在 componentWillMount:

中添加到键盘的 eventListener,导致组件重新渲染
 componentWillMount() {
    this.keyboardWillShowListener = Keyboard.addListener(
        "keyboardWillShow",
        this.keyboardWillShow.bind(this)
    );
}

keyboardWillShow(e) {
    this.setState({
        height:
            Dimensions.get("window").height * 0.9 - e.endCoordinates.height
    });
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
}

这会影响性能,我想避免不必要的重新渲染。

问题:
1. React-Navigation 的 ScreenProps 是否可以设置 Keyboard 的动态高度(取决于设备)?
2. 是否可以用 React-Navigation 的 state.params?
做同样的事情 3. 除了应用 KeyboardAvoidingView 或 this module ?

之外,还有其他方法可以解决此问题吗?

这是我所做的:

如果应用有 "Authorization / Log-in / Sign-up screen" 那么:

  1. 在 componentWillMount 中按照说明添加 KeyboardListeners here:

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    
  2. 在页面上添加 autoFocus 到电子邮件/phone 号码/任何其他 "first" TextInput,以便在屏幕加载时弹出键盘-up.

  3. 在用作 KeyboardListener 的 _keyboardDidShow 函数中,执行以下操作:

    _keyboardDidShow(e) {
        this.props.navigation.setParams({
            keyboardHeight: e.endCoordinates.height,
            normalHeight: Dimensions.get('window').height, 
            shortHeight: Dimensions.get('window').height - e.endCoordinates.height, 
        }); 
    }
    

    Dimensions 是 React-Native 的 API,不要忘记像导入任何 React-Native 组件一样导入它。

  4. 之后,在重定向到下一个页面时,传递这些参数,不要忘记继续将它们传递到其他屏幕,以免丢失此数据:

    this.props.navigation.navigate('pageName', { params: this.props.navigation.state.params });
    

我还需要一个钩子,所以这就是我如何获得键盘的高度(很大程度上受到其他答案的启发),代码示例在 TypeScript 中:

import { useEffect, useState } from 'react';
import { Keyboard, KeyboardEvent } from 'react-native';

export const useKeyboard = () => {
  const [keyboardHeight, setKeyboardHeight] = useState(0);

  function onKeyboardDidShow(e: KeyboardEvent) { // Remove type here if not using TypeScript
    setKeyboardHeight(e.endCoordinates.height);
  }

  function onKeyboardDidHide() {
    setKeyboardHeight(0);
  }

  useEffect(() => {
    const showSubscription = Keyboard.addListener('keyboardDidShow', onKeyboardDidShow);
    const hideSubscription = Keyboard.addListener('keyboardDidHide', onKeyboardDidHide);
    return () => {
      showSubscription.remove();
      hideSubscription.remove();
    };
  }, []);

  return keyboardHeight;
};

然后在你的组件中:

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

只是想补充以上答案,使用 keyboardWillShowkeyboardWillHide 而不是 keyboardDidShowkeyboardDidHide 看起来会好得多。它只是运行得更快,因此看起来更流畅。

致那些仍在寻找此问题答案的人 now you can use hooks

import { useKeyboard } from '@react-native-community/hooks'

//Then keyboard like this 

const keyboard = useKeyboard()

console.log('keyboard isKeyboardShow: ', keyboard.keyboardShown)
console.log('keyboard keyboardHeight: ', keyboard.keyboardHeight)