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

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

当前回答

这刚刚被更新和记录!不再有隐藏的诡计。

import { Keyboard } from 'react-native'

// Hide that keyboard!
Keyboard.dismiss()

Github链接

其他回答

有很多方法可以处理这个问题,上面的答案不包括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}

使用ScrollView代替带有keyboardShouldPersistTaps={"always"}属性的View。当我们点击屏幕内的任何地方时,它会隐藏键盘

<ScrollView keyboardShouldPersistTaps={"always"}>
 <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>

我刚刚使用最新的React Native版本(0.4.2)进行了测试,当你点击其他地方时,键盘就会消失。

供你参考:你可以设置一个回调函数,当你解散键盘时,通过将它分配给“onenditing”道具来执行。

我们可以在没有react-native反馈的情况下使用keyboard和tochable

const DismissKeyboard = ({ children }) => (
  <TouchableWithoutFeedback
    onPress={() => Keyboard.dismiss()}
  >
    {children}
  </TouchableWithoutFeedback>
);

并这样使用它:

const App = () => (
  <DismissKeyboard>
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="username"
        keyboardType="numeric"
      />
      <TextInput
        style={styles.input}
        placeholder="password"
      />
    </View>
  </DismissKeyboard>
);

我还在这里用源代码进行了解释。

简单的答案是使用ScrollView而不是View,并将scrollable属性设置为false(尽管可能需要调整一些样式)。

这样,当我敲击其他地方时,键盘就会消失。这可能是react-native的一个问题,但点击事件似乎只被ScrollViews处理,这导致了上述行为。

编辑:感谢jllodra。请注意,如果你直接点击到另一个文本输入,然后在外面,键盘仍然不会隐藏。