适用于Android的TextInput上的onKeyPress方法

问题描述 投票:3回答:4

我一直试图在TextInputreact-native内捕捉键盘的事件。

通过阅读组件的文档(https://facebook.github.io/react-native/docs/textinput.html),我注意到onKeyPress函数完全符合我的需要。但它仅被标记为ios。我没有发现任何有关android解决方法的问题,除了这个问题(https://github.com/facebook/react-native/issues/1882)已经暂停了几个月了...

我需要做的是在按下Backspace时调用一个特定的方法,看起来它现在只能用于ios ......

你们知道任何解决方法吗?

提前致谢 :)

android react-native textinput onkeypress
4个回答
2
投票

我也遇到过这个问题。我可以告诉你,我做了什么。它不优雅,但它会完成这项工作,直到它也为Android实现。

在Android中你可以在Activity中使用handle key events。此外,你可以send events to JavaScript。这就是你需要的一切。

在js文件(例如componentDidMount)中添加监听器。

DeviceEventEmitter.addListener('onKeyPressed', yourFunction)

在您的MainActivity中添加这样的内容。

public boolean onKeyUp(int keyCode, KeyEvent event) {
   WritableMap params;
   // params.put something
   // filter only Backspace events if you wish etc.
   reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                           .emit("onKeyPressed", params);
}

每按一次键就会发送一次。不要忘记删除监听器(例如componentDidUnmount或不再需要它时)。此外,如果你有多个TextInput,跟踪焦点,所以你不要混淆。

希望这可以帮助。


2
投票

onKeyPress现在支持Android。

从版本v0.55.2commit

注意Android上不支持硬件键盘输入,只有软键盘输入。

这意味着,如果您在Android模拟器上进行测试并在计算机键盘上键入,则不会处理这些输入。因此,继续使用鼠标按下模拟器上的软键盘。


1
投票

在MainActivity.java中添加它

import com.facebook.react.modules.core.DeviceEventManagerModule;
import android.view.KeyEvent;

...

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    getReactNativeHost().getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("onKeyPressed", keyCode);
    return super.onKeyUp(keyCode, event);
}

现在,这将返回与按下的按钮对应的keyCode

将其添加到您的组件以收听发出的keyCode,例如我在componentWillMount中添加了监听器

componentWillMount = () => {
    this.keyPressedListener = DeviceEventEmitter.addListener('onKeyPressed', yourFunction);
}

根据您的要求处理您的函数,并且不要忘记随后删除监听器。


0
投票

您可以使用TextInput的onChangeText并在提供给onChangeText的函数内部,您可以检查最后输入的文本是否比TextInput中的早期文本少一个字符。如果有,则表示用户按下了退格键,您可以触发/调用您的特定方法。

 class SearchScreenBase extends Component {

  constructor(props) {
    super(props);
    this.state = { lastText: '',
    };
    // Bind callback methods to make `this` the correct context.
    this._onChange = this._onChange.bind(this);
   }
   _onChange(newText) {
      var oldText = this.state.lastText;
      if(newText.length === (oldText.length-1)){
         //INSERT TRIGGER FUNCTION HERE
      }
      this.setState({
               lastText: newText
      });
   }
   render() {
    return (
      <TextInput
        onChangeText = {this._onChange}
        editable = {true}
        maxLength = {40}
      />
    );
  }
}

它对我很有用。

© www.soinside.com 2019 - 2024. All rights reserved.