React Native API之—— Keyboard键盘相关
最近在做React Native
开发app,需要对键盘进行操作。查阅文档,发现了一个api——Keyboard
。
Keyboard
模块用来控制键盘相关的事件。
说明
Keyboard
模块可以监听原生键盘事件以做出相应回应,比如收回键盘。
方法
addListener()
static addListener(eventName, callback)
addListener
用于注册一个 JavaScript 函数来监听处理原生键盘通知事件。
eventName有以下几种:
- keyboardWillShow
- keyboardDidShow
- keyboardWillHide
- keyboardDidHide
- keyboardWillChangeFrame
- keyboardDidChangeFrame
项目中用到了两个keyboardDidShow
,keyboardDidHide
removeListener()
static removeListener(eventName, callback)
移除某个类型事件的监听函数。
相关代码
import React from 'react'
import {
View,
Text,
Image,
Keyboard
} from 'react-native'
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
}
componentWillUnmount() {
this.keyboardDidShowListener?.remove();
this.keyboardDidHideListener?.remove();
}
_keyboardDidShow = (e) => {
if (Global.isIOS) {
this.setState({
keyboardHeight: e?.endCoordinates?.height
})
}
}
_keyboardDidHide = (e) => {
this.setState({
keyboardHeight: 0
})
}
转载自:https://juejin.cn/post/7042188996188831781