在 react-native 中隐藏键盘

新手上路,请多包涵

如果我点击文本输入,我希望能够点击其他地方以再次关闭键盘(虽然不是返回键)。在我阅读的所有教程和博客文章中,我都没有找到与此相关的任何信息。

这个基本示例仍然不适用于模拟器中的 react-native 0.4.2。还不能在我的 iPhone 上试用。

 <View style={styles.container}>
  <Text style={styles.welcome}>
    Welcome to React Native!
  </Text>
  <Text style={styles.instructions}>
    To get started, edit index.ios.js
  </Text>
  <Text style={styles.instructions}>
    Press Cmd+R to reload,{'\n'}
    Cmd+D or shake for dev menu
  </Text>
  <TextInput
    style={{height: 40, borderColor: 'gray', borderWidth: 1}}
    onEndEditing={this.clearFocus}
  />
</View>

原文由 TurboFish 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

如果您有 keyboardType='numeric' ,键盘不关闭的问题会变得更加严重,因为没有办法关闭它。

用 ScrollView 替换 View 不是一个正确的解决方案,就好像你有多个 textInput s 或 button s,在键盘启动时点击它们只会关闭键盘。

正确的方法是用 TouchableWithoutFeedback 封装 View 并调用 Keyboard.dismiss()

编辑:您现在可以将 ScrollViewkeyboardShouldPersistTaps='handled' 一起使用,仅在儿童未处理轻按时关闭键盘(即轻按其他文本输入或按钮)

如果你有

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

将其更改为

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

或者

import {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

编辑:您还可以创建一个高阶组件来关闭键盘。

 import React from 'react';
import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

像这样简单地使用它

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

注意:需要 accessible={false} 才能继续通过 VoiceOver 访问输入表单。有视力障碍的人会感谢你的!

原文由 Eric Kim 发布,翻译遵循 CC BY-SA 4.0 许可协议

将此用于自定义解雇

var dismissKeyboard = require('dismissKeyboard');

var TestView = React.createClass({
    render: function(){
        return (
            <TouchableWithoutFeedback
                onPress={dismissKeyboard}>
                <View />
            </TouchableWithoutFeedback>
        )
    }
})

原文由 syarul 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题