react-native 按键事件

react-native默认没有keyEvent,这里主要介绍如何实现将keyEvent(按键事件或者遥控器事件)发送给页面:

native java代码:

public class MainActivity extends ReactActivity {

    private void sendEvent(ReactContext reactContext,
                           String eventName,
                           @Nullable WritableMap params) {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, params);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
        WritableMap params = Arguments.createMap();
        params.putInt("which", event.getKeyCode());
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            sendEvent(reactContext, "keydown", params);
        } else if (event.getAction() == KeyEvent.ACTION_UP) {
            sendEvent(reactContext, "keyup", params);
        }
        return super.dispatchKeyEvent(event);
    }
}

js 代码:

  componentDidMount() {
    DeviceEventEmitter.addListener('keydown', function(e) {
      console.log('keycode: '+e.which);
    });
  }

你可能感兴趣的:(react-native 按键事件)