在不使用输入字段的情况下确定在 React Native 上按下了哪个键

Determine Which Key is Pressed on React Native Without Using Input Field

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

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

这是我的解决方案:

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