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

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

当前回答

更新了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只能有一个子元素,所以你需要把它下面的所有元素都包装在一个视图中,如上所示。

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

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

onStartShouldSetResponder道具停止触摸事件传播到TouchableWithoutFeedback元素。

<TouchableWithoutFeedback onPress={...}>
  <View>
    <ScrollView>
      <View onStartShouldSetResponder={() => true}>
        // Scrollable content
      </View>
    </ScrollView>
  </View>
</TouchableWithoutFeedback>

这是最简单的方法

import {Keyboard} from 'react-native'

然后使用函数Keyboard.dismiss()

这是所有。

下面是我代码的截图,这样你可以更快地理解。

现在用TouchableWithoutFeedback和onPress函数来包装整个视图是keyboard。dismiss()

下面是一个例子

这样,如果用户点击屏幕上的任何地方,不包括textInput字段,键盘将被解散。

Keyboard.dismiss()就会这样做。但有时它可能会失去焦点,键盘将无法找到ref。最一致的方法是将ref=_ref放到textInput中,当你需要解除时执行_ref.blur(),当你需要恢复键盘时执行_ref.focus()。