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

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

当前回答

将组件包装在TouchableWithoutFeedback中可能会导致一些奇怪的滚动行为和其他问题。我更喜欢用onStartShouldSetResponder属性填充在视图中包装我最顶层的应用程序。这将允许我处理所有未处理的触摸,然后解散键盘。重要的是,由于handler函数返回false,所以触摸事件会像正常情况一样向上传播。

 handleUnhandledTouches(){
   Keyboard.dismiss
   return false;
 }

 render(){
    <View style={{ flex: 1 }} onStartShouldSetResponder={this.handleUnhandledTouches}>
       <MyApp>
    </View>
  }

其他回答

你可以像下面这样从react-native导入键盘:

import { Keyboard } from 'react-native';

在你的代码中可以是这样的:

render() {
    return (
      <TextInput
        onSubmit={Keyboard.dismiss}
      />
    );
  }

静态解散() 解散活动键盘并移除焦点。

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

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

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

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

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

更新了React Native 0.39中ScrollView的用法

<ScrollView scrollEnabled={false} contentContainerStyle={{flex: 1}} />

虽然,两个TextInput框仍然有一个问题。如。用户名和密码表单现在在切换输入时将忽略键盘。很想得到一些建议,以保持键盘在使用ScrollView切换TextInputs之间。

使用React Native的Keyboard.dismiss()

更新后的答案

React Native在键盘上暴露了静态的dismiss()方法,因此更新的方法是:

import { Keyboard } from 'react-native'; 

Keyboard.dismiss()

原来的答案

使用React Native的遣散键盘库。

我有一个非常相似的问题,感觉我是唯一一个没有得到它。

ScrollViews

如果你有一个ScrollView,或者任何从它继承的东西,比如ListView,你可以添加一个道具,它会根据按下或拖动事件自动取消键盘。

道具是keyboardDismissMode,值可以为none、interactive或on-drag。你可以在这里阅读更多。

常规的观点

如果你有一个ScrollView以外的东西,你想要任何按键来解除键盘,你可以使用一个简单的TouchableWithoutFeedback,并让onPress使用React Native的实用程序库来解除键盘。

在你的例子中,你可以这样做:

var DismissKeyboard = require('dismissKeyboard'); // Require React Native's utility library.

// Wrap your view with a TouchableWithoutFeedback component like so.

<View style={styles.container}>

  <TouchableWithoutFeedback onPress={ () => { DismissKeyboard() } }>

    <View>

      <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}} />

    </View>

  </TouchableWithoutFeedback>

</View>

注意:TouchableWithoutFeedback只能有一个子元素,所以你需要把它下面的所有元素都包装在一个视图中,如上所示。