Fra*_*nto 4 android react-native react-native-textinput
这是Android的本机问题。
当 TextInput 被聚焦时,如何处理 Android 中的后退按钮?
BackHandler.addEventListener('hardwareBackPress'. () => {})如果 TextInput 为焦点,则不会捕获任何事件。它会自动关闭键盘。
(实际上我想要实现的是在按下后退按钮并关闭键盘时移除光标)
你可以玩这个世博小吃来了解我在说什么:
我相信这是正确的行为,但要实现您想要的,您可以使用键盘检测键盘本身隐藏而不是使用键盘(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...
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢这种方法而不是使用 TextInput 的 onKeyPress 事件,因为 onKeyPress 不会读取硬件键盘后退按钮,所以如果用户有一个带有硬件后退按钮的设备,就像一些 Android 设备那样,onKeyPress 将无法工作,这提供了一个更一致的体验。
您可以自行处理它,TextInput而不是使用BackHandler. 你可以通过onKeyPressprop来做到这一点
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}
/>
Run Code Online (Sandbox Code Playgroud)
另外值得注意的是,在 Android 上,此事件只会在软件键盘上触发,因此,如果您在模拟器上运行并使用计算机键盘上的退格键,则此事件将不起作用。
| 归档时间: |
|
| 查看次数: |
4339 次 |
| 最近记录: |