React Native - Keyboard API使用详解(监听处理键盘事件)

参考:

React Native - Keyboard API使用详解(监听处理键盘事件)

当我们点击输入框时,手机的软键盘会自动弹出,以便用户进行输入。
但有时我们想在键盘弹出时对页面布局做个调整,
或者在程序中使用代码收起这个软键盘,这些借助 React Native 框架提供的 Keyboard API 就可以实现。

一、Keyboard API 提供的方法

Keyboard API 提供如下的静态函数供开发者使用。

1,addListener(eventName, callback)

(1)这个函数用来加载一个指定事件的事件监听器,函数中的 eventName 可以是如下值:

  • keyboardWillShow:软键盘将要显示
  • keyboardDidShow:软键盘显示完毕
  • keyboardWillHide:软键盘将要收起
  • keyboardDidHide:软键盘收起完毕
  • keyboardWillChangeFrame:软件盘的 frame 将要改变
  • keyboardDidChangeFrame:软件盘的 frame 改变完毕

(2)这个函数返回一个对象。我们可以保存这个对象,在需要释放事件监听器时,调用这个对象的 remove 方法。

2,removeListener(eventName, callback)

这个函数用来释放一个特定的键盘事件监听器。

3,removeAllListener(eventName)

这个函数用来释放一个指定键盘事件的所有事件监听器。

4,dismiss()

这个方法让操作系统收起软键盘。

二、event 参数值

所有的键盘事件处理函数都能收到一个 event 参数,不过在不同平台下 event 参数可以取到的值不太一样。

1,Android 平台可以取到的值

  • event.endCoordinates.screenX
  • event.endCoordinates.screenY
  • event.endCoordinates.width
  • event.endCoordinates.height

2,iOS 平台可以取到的值

  • event.easing:这个值始终是 keyboard
  • evnet.duration:记录软键盘弹出动画的持续事件,单位是毫秒
  • event.startCoordinates.screenX
  • event.startCoordinates.screenY
  • event.startCoordinates.width
  • event.startCoordinates.height
  • event.endCoordinates.screenX
  • event.endCoordinates.screenY
  • event.endCoordinates.width
  • event.endCoordinates.height

三、使用样例

1,效果图

在这里插入图片描述
在这里插入图片描述

(1)在组件加载时就开始监听虚拟键盘的弹出/隐藏事件,一旦虚拟键盘状态发生变化,输入框下方便会实时显示当前状态。

(2)虚拟键盘打开后,除了点击键盘上的“完成”按钮外可以收起键盘外。点击输入框右侧的“收起键盘”按钮也可以达到同样效果。

2,样例代码:


import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    TextInput,
    View,
    Text,
    Keyboard,
} from 'react-native';

const TAG = 'KeyboardTest=============';
export default class extends Component {

    constructor(props) {
        super(props);
        this.keyboardDidShowListener = null;
        this.keyboardDidHideListener = null;
        this.state = {
            KeyboardShown: false,
        };
    }

    componentWillMount() {
        //监听键盘弹出事件
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow',
            this.keyboardDidShowHandler.bind(this));
        //监听键盘隐藏事件
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide',
            this.keyboardDidHideHandler.bind(this));
    }

    componentWillUnmount() {
        //卸载键盘弹出事件监听
        if (this.keyboardDidShowListener != null) {
            this.keyboardDidShowListener.remove();
        }
        //卸载键盘隐藏事件监听
        if (this.keyboardDidHideListener != null) {
            this.keyboardDidHideListener.remove();
        }
    }

    //键盘弹出事件响应
    keyboardDidShowHandler(event) {
        this.setState({
            KeyboardShown: true,
        });
        this.printLog('show', event);
    }

    //键盘隐藏事件响应
    keyboardDidHideHandler(event) {
        this.setState({
            KeyboardShown: false,
        });
        this.printLog('hide', event);
    }

    //强制隐藏键盘
    dismissKeyboard() {
        Keyboard.dismiss();
        console.log(TAG, '输入框当前焦点状态:' + this.refs.bottomInput.isFocused());
    }

    printLog(method, event) {
        console.log(TAG, method, '  endCoordinates.screenX=', event.endCoordinates.screenX);
        console.log(TAG, method, '  endCoordinates.screenY=', event.endCoordinates.screenY);
        console.log(TAG, method, '  endCoordinates.width=', event.endCoordinates.width);
        console.log(TAG, method, '  endCoordinates.height=', event.endCoordinates.height);
        // console.log(TAG, method, ' startCoordinates=', event.startCoordinates.screenX);
        // console.log(TAG, method, ' startCoordinates=', event.startCoordinates.screenY);
        // console.log(TAG, method, ' startCoordinates=', event.startCoordinates.width);
        // console.log(TAG, method, ' startCoordinates=', event.startCoordinates.height);
        console.log('=================================================================');
    }

    render() {
        return (
            <View style={[styles.container]}>
                <View style={[styles.flexDirection, styles.inputHeight]}>
                    <TextInput style={styles.textInputStyle} ref="bottomInput"/>
                    <Text style={styles.buttonStyle}
                          onPress={this.dismissKeyboard.bind(this)}>
                        收起键盘
                    </Text>
                </View>
                <Text>
                    当前键盘状态:{this.state.KeyboardShown ? '打开' : '关闭'}
                </Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 15,
    },
    flexDirection: {
        flexDirection: 'row',
    },
    inputHeight: {
        height: 35,
        alignItems: 'center',
    },
    textInputStyle: {
        flex: 1,
        height: 35,
        fontSize: 18,
    },
    buttonStyle: {
        fontSize: 20,
        color: 'white',
        width: 100,
        textAlign: 'center',
        backgroundColor: '#4CA300',
    },
});



3,打印日志:

//打开键盘
'KeyboardTest=============', 'show', '  endCoordinates.screenX=', 0
'KeyboardTest=============', 'show', '  endCoordinates.screenY=', 279.6666564941406
'KeyboardTest=============', 'show', '  endCoordinates.width=', 360
'KeyboardTest=============', 'show', '  endCoordinates.height=', 316.3333435058594
=================================================================
//键盘上的关闭按钮
'KeyboardTest=============', 'hide', '  endCoordinates.screenX=', 0
'KeyboardTest=============', 'hide', '  endCoordinates.screenY=', 572
'KeyboardTest=============', 'hide', '  endCoordinates.width=', 360
'KeyboardTest=============', 'hide', '  endCoordinates.height=', 0
=================================================================
//打开键盘
'KeyboardTest=============', 'show', '  endCoordinates.screenX=', 0
'KeyboardTest=============', 'show', '  endCoordinates.screenY=', 279.6666564941406
'KeyboardTest=============', 'show', '  endCoordinates.width=', 360
'KeyboardTest=============', 'show', '  endCoordinates.height=', 316.3333435058594
=================================================================
//rn强制关闭键盘
'KeyboardTest=============', '输入框当前焦点状态:false'
'KeyboardTest=============', 'hide', '  endCoordinates.screenX=', 0
'KeyboardTest=============', 'hide', '  endCoordinates.screenY=', 572
'KeyboardTest=============', 'hide', '  endCoordinates.width=', 360
'KeyboardTest=============', 'hide', '  endCoordinates.height=', 0
=================================================================



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Native的 `react-native-android-keyboard-adjust` 库可以用来调整安卓键盘的行为。在0.63版本中,使用方法如下: 1. 安装库 使用以下命令安装库: ``` npm install react-native-android-keyboard-adjust ``` 2. 链接原生代码 使用以下命令来链接原生代码: ``` npx react-native link react-native-android-keyboard-adjust ``` 或者手动链接,按照以下步骤: (1) 在 `android/settings.gradle` 文件中添加以下代码: ``` include ':react-native-android-keyboard-adjust' project(':react-native-android-keyboard-adjust').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-keyboard-adjust/android') ``` (2) 在 `android/app/build.gradle` 文件中添加以下代码: ``` dependencies { // ... implementation project(':react-native-android-keyboard-adjust') } ``` (3) 在 `MainApplication.java` 文件中导入以下代码: ``` import com.reactnativeandroidkeyboardadjust.ReactNativeAndroidKeyboardAdjustPackage; ``` (4) 在 `MainApplication.java` 文件的 `getPackages()` 方法中添加以下代码: ``` new ReactNativeAndroidKeyboardAdjustPackage() ``` 3. 使用 在需要调整键盘行为的组件上,添加 `androidKeyboardAdjust` 属性,值可以为以下三种: - `none`: 不调整键盘行为 - `pan`: 键盘出现时,组件会向上滚动,以避免被键盘遮挡 - `resize`: 键盘出现时,组件会自动调整大小,以避免被键盘遮挡 例如: ```jsx <TextInput androidKeyboardAdjust="pan" // ... /> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值