RN的文本框 获取焦点但隐藏键盘 React Native TextInput onfocus but hide keyboard

After a lot of research, I was able to find a monkey patch for this issue on Android (I’m currently developing an Android app only).

We should create a Native Module that calls InputMethodManager to close the keyboard when visible and add an onFocus function on our TextInput that calls the Native’s keyboard dismissal function.

Here’s how to do it:

Create a Keyboard Native Module
KeyboardModule.java
package com.xxx.xxx;

import android.app.Activity;
import android.view.inputmethod.InputMethodManager;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;

public class KeyboardModule extends ReactContextBaseJavaModule {

    public KeyboardModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "KeyboardFunctionalities";
    }

    @ReactMethod
    public void hideKeyboard() {
        final Activity activity = getCurrentActivity();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    }
}

KeyboardPackage.java

package com.xxx.xxx;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class KeyboardPackage implements ReactPackage {

    @Override
    public List createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List createNativeModules(
            ReactApplicationContext reactContext) {
        List modules = new ArrayList<>();

        modules.add(new KeyboardModule(reactContext));

        return modules;
    }

}

Register it in MainApplication.java

@Override
    protected List getPackages() {
      return Arrays.asList(
          new MainReactPackage(),
            ...,
            new KeyboardPackage()
      );
    }

Use it in your React Native code:

import { TextInput, NativeModules } from "react-native"

render(){
  return(
     NativeModules.KeyboardFunctionalities.hideKeyboard() } />
  )
}

你可能感兴趣的:(Android,RN)