如何在 React Native 中检测键盘何时打开或关闭 [英] How to detect when keyboard is opened or closed in React Native

查看:85
本文介绍了如何在 React Native 中检测键盘何时打开或关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测用户是否在 React Native 中关闭键盘,我想在用户关闭键盘时调用一个函数.

How to detect if user close the keyboard in react native, I want to call a function when user closed the keyboard.

如果您也能回答检测到键盘是否打开,我们将不胜感激,谢谢.

and if you can answer to detect keyboard is open too it will be appreciated, thanks.

我正在使用 React Native 最新 version 0.56

I'm on the react native latest version 0.56

推荐答案

1.您可以使用来自 Facebook 的 键盘类.H3>

这是一个示例代码.

1. You can use Keyboard class from facebook.

Here is a sample code.

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {
  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }
    
  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }
    
  _keyboardDidShow () {
    alert('Keyboard Shown');
  }
    
  _keyboardDidHide () {
    alert('Keyboard Hidden');
  }
    
  render() {
    return (
      <TextInput
        onSubmitEditing={Keyboard.dismiss}
      />
    );
  }
}

###2.您也可以使用其他一些 npm 依赖项,例如 react-native-keyboard-听众.

###2. You can use some other npm dependency also, like react-native-keyboard-listener.

将组件导入到要使用的文件中:

Import the component into the file you want to use it:

import KeyboardListener from 'react-native-keyboard-listener';

直接在您的代码中使用该组件.组件不会渲染任何东西

Use the component directly in your code. The component won't render anything

<View>
  <KeyboardListener
    onWillShow={() => { this.setState({ keyboardOpen: true }); }}
    onWillHide={() => { this.setState({ keyboardOpen: false }); }}
  />
</View>

要安装此依赖项,请运行以下命令.

To install this dependency run below command.

npm install --save react-native-keyboard-listener

选择您觉得更方便的任何一个.

这篇关于如何在 React Native 中检测键盘何时打开或关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆