首页 > 解决方案 > 在不使用输入字段的情况下确定在 React Native 上按下了哪个键

问题描述

有了 Mac 上硅芯片的机会。我们开始使用 React Native 开发 Mac 应用程序。我们没有使用任何输入字段,但我们需要确定当用户专注于我们的应用程序时从键盘按下了哪个键。基本上我们想在用户使用我们的应用程序时监听所有键盘事件。解决这个问题的最佳方法是什么?

标签: react-nativereact-native-androidreact-native-ios

解决方案


如果您在 macOS 上使用 react-native,那么您可能会使用react-native-webelectron直接在 Web 浏览器中使用。

这是我的解决方案:

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class App extends Component {
    handleKeyDown = (e) => {
        console.log(`${e.code}`);
        // Do your stuff...
    };

    componentDidMount = () => {
        document.onkeydown = this.handleKeyDown;
    };

    componentWillUnmount = () => {
        document.onkeydown = null;
    };

    render = () => {
        return (
            <View>
                <Text>{'Example'}</Text>
            </View>
        );
    };
}

推荐阅读