首页 > 解决方案 > React Native 中的键盘处理

问题描述

如何让您的应用程序优雅地响应键盘外观?到目前为止,我已经尝试过键盘感知滚动、键盘间隔和键盘避免视图

键盘避免视图根本没有帮助我已经尝试了几次,但它甚至没有响应键盘的外观。

Keyboardspacer 可以正常工作,但在许多情况下,它会破坏其他视图,从而破坏整个 UI

当应用程序中没有滚动时,键盘感知滚动有效,但对于长表单则不起作用。

android:windowSoftInputMode="adjustPan" 仅适用于安卓

当键盘出现时,我们还有哪些其他选项可以让应用程序优雅地响应。

你在你的应用程序中使用什么?

标签: react-native

解决方案


如果这些库都不能满足您的需求,您可以使用键盘模块(https://facebook.github.io/react-native/docs/keyboard上的文档)手动调整视图键盘打开或关闭,如下所示:

import * as React from 'react';
import { Keyboard } from 'react-native';

class MyComponent extends React.Component {
  componentDidMount() {
      this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide);
      this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow);
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
    this.keyboardDidShowListener.remove();
  }

  keyboardDidShow = () => {
      //Fix your view for when a keyboard shows
  };

  keyboardDidHide = () => {
      //Fix your view for when a keyboard hides
  };

    //Rest of component...

}

推荐阅读