如果我点击一个文本输入,我希望能够点击其他地方,以便再次取消键盘(不是返回键)。在我读过的所有教程和博客文章中,我没有发现一丁点关于这方面的信息。

这个基本的例子在模拟器中的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>

当前回答

使用ScrollView而不是View,并将keyboardShouldPersistTaps属性设置为false。

<ScrollView style={styles.container} keyboardShouldPersistTaps={false}>
    <TextInput
        placeholder="Post Title"
        onChange={(event) => this.updateTitle(event.nativeEvent.text)}
        style={styles.default}/>
 </ScrollView>

其他回答

用以下内容包装整个组件:

import { TouchableWithoutFeedback, Keyboard } from 'react-native'

<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
...
</TouchableWithoutFeedback>

为我工作

如果你有keyboardType='numeric',键盘不解散的问题会变得更严重,因为没有办法解散它。

用ScrollView替换View不是一个正确的解决方案,因为如果你有多个textinput或按钮,在键盘打开时点击它们只会让键盘消失。

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

编辑:你现在可以使用带有keyboardShouldPersistTaps='handled'的ScrollView来只在点击没有被孩子处理的时候解散键盘。点击其他文本,输入或按钮)

如果你有

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

改为

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

or

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继续访问。视障人士会感谢你的!

有很多方法可以处理这个问题,上面的答案不包括returnType,因为它当时不包括在react-native中。

1:你可以通过在ScrollView中包装你的组件来解决这个问题,默认情况下,如果我们按下某个地方,ScrollView会关闭键盘。但如果你想使用ScrollView但禁用此效果。你可以使用pointerEvent道具来scrollView pointerEvents = 'none'。

2:如果你想关闭键盘按钮按下,你可以使用键盘从反应本机

import {Keyboard} from 'react-native' 在那个按钮的onPress里面,你可以使用keyboard .dismiss()'。

3:你也可以在点击键盘上的返回键时关闭键盘, 注意:如果你的键盘类型是数字,你将没有返回键。 你可以通过给它一个道具returnKeyType来启用它。 或者你可以使用onSubmitEditing={键盘。当我们按回车键时,它就会被调用。如果你想在失去焦点时忽略键盘,你可以使用onBlur prop, onBlur = {keyboard .dismiss}

隐藏键盘使用 TextInput内部的Keyboard.dismiss()

如果我没有弄错的话,最新版本的React Native已经解决了这个问题,可以通过敲击键盘来消除键盘。