6

这是Android的react-native问题。

当 TextInput 聚焦时,如何处理 Android 中的后退按钮? BackHandler.addEventListener('hardwareBackPress'. () => {})如果 TextInput 获得焦点,则不会捕获任何事件。它会自动关闭键盘。

(实际上我想要实现的是在按下后退按钮并关闭键盘时移除光标)

你可以玩这个世博小吃来理解我在说什么:

4

3 回答 3

8

我相信这是正确的行为,但要做出你想要的,你可以通过使用键盘来检测键盘本身隐藏(https://facebook.github.io/react-native/docs/keyboard上的文档)

import * as React from 'react';
import { Keyboard } from 'react-native';

class MyComponent extends React.Component {
  componentDidMount() {
      this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide);
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
  }

  keyboardDidHide = () => {
      this.input.blur();
  };

    //Rest of component...

}

我更喜欢这种方法而不是使用 TextInput 中的 onKeyPress 事件,因为 onKeyPress 不会读取硬件键盘后按,所以如果用户有一个带有硬件后退按钮的设备,就像某些 Android 设备一样,onKeyPress 将不起作用,这提供了一个更一致的体验。

于 2018-11-07T14:15:56.823 回答
2

@Danilo 答案确实有效,但它必须应用于所有文本输入。我最终使用了 Danilo 的解决方案,稍作改动。

Keyboard.dismiss()确实模糊了任何活动的TextInput,所以在keyboardDidHide事件上我只调用Keyboard.dismiss()(尽管键盘只是通过按下后退按钮被解除)。我只需要将它添加到我的主要组件中。

import * as React from 'react';
import { Keyboard } from 'react-native';

class MyComponent extends React.Component {
  componentDidMount() {
      this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide);
  }

  componentWillUnmount() {
    this.keyboardDidHideListener.remove();
  }

  keyboardDidHide = () => {
      Keyboard.dismiss();
  };

    //Rest of component...

}

您可以在这个博览会小吃中测试这个解决方案。

如果您的应用程序有多个 TextInputs,onSubmitEditing 将焦点放在下一个 TextInput,这就是我使它工作的方式:

  ...

  keyboardDidHide = () => {
      this.keyboardTimeout = setTimeout(() => Keyboard.dismiss(), 300)
  };

  keyboardDidShow = () => {
      clearTimeout(this.keyboardTimeout)
  };

  ...
于 2018-11-07T20:34:37.197 回答
1

您将TextInput自行处理它,而不是使用BackHandler. 你可以通过onKeyPress道具做到这一点

constructor(props){
  super(props)
  this.inputRef = React.createRef()
}

<TextInput
  onKeyPress={({ nativeEvent }) => {
    if(nativeEvent.key === 'Backspace'){
      //your code
      // if you want to remove focus then you can use a ref
      Keyboard.dismiss();
      this.inputRef.blur()
    }
  }}
  ref={this.inputRef}
/>

另外需要注意的是,在 Android 上,此事件只会在软件键盘上触发,因此如果您在模拟器上运行并使用计算机键盘上的退格键,这将不起作用。

于 2018-11-07T14:14:46.327 回答