当前位置: 移动技术网 > IT编程>开发语言>JavaScript > ReactNative之键盘Keyboard的弹出与消失示例

ReactNative之键盘Keyboard的弹出与消失示例

2017年12月12日  | 移动技术网IT编程  | 我要评论

在开发中经常遇到需要输入的地方,所以就学习了一下reactnative键盘keyboard的弹出与消失的方法,留个笔记。

今天我们来说下rn对键盘事件的支持。

在react-native 的component组件中有个keyboard.

github地址如下:https://github.com/facebook/react-native/tree/770091f3c13f7c1bd77c50f979d89a774001fbf0/libraries/components/keyboard

我们先来看下官方提供的例子,监听键盘的弹出与消失。demo如下:

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} 
   /> 
  ); 
 } 
} 

keyboard支持的监听事件如下:

@param {string} nativeevent the `nativeevent` is the string that identifies the event you're listening for. this can be any of the following: 
- `keyboardwillshow` 
- `keyboarddidshow` 
- `keyboardwillhide` 
- `keyboarddidhide` 
- `keyboardwillchangeframe` 
- `keyboarddidchangeframe` 

使用的时候需要测试下android和ios下监听的事件是否都ok。

踩坑如下:

android 对keyboardwillshow 监听不到。

同样,我们在源码里可以找到使键盘消失的函数

/** 
 * dismisses the active keyboard and removes focus. 
 */ 
dismiss () { 
 dismisskeyboard(); 
} 

我们如果需要使用时,可以如下:

const dismisskeyboard = require('dismisskeyboard'); 
dismisskeyboard(); 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网