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

这个基本的例子在模拟器中的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的新手,在制作演示应用程序时遇到了完全相同的问题。如果你使用onStartShouldSetResponder道具(此处描述),你可以在一个普通的旧React. view上抓取触摸。很想听听更多经验丰富的反应者对这一策略的看法/如果有更好的策略,但这对我来说是有效的:

containerTouched(event) {
  this.refs.textInput.blur();
  return false;
}

render() {
  <View onStartShouldSetResponder={this.containerTouched.bind(this)}>
    <TextInput ref='textInput' />
  </View>
}

这里需要注意两点。首先,正如这里讨论的,还没有结束所有子视图编辑的方法,所以我们必须直接引用TextInput来模糊它。其次,onStartShouldSetResponder被它上面的其他可触摸控件截获。因此,在容器视图中点击TouchableHighlight等(包括另一个TextInput)将不会触发事件。但是,在容器视图中单击Image仍然会关闭键盘。

其他回答

在ScrollView中使用keyboardShouldPersistTaps,你可以传入“handled”,它处理人们所说的使用ScrollView带来的问题。这是文档中关于使用'handled'的说明:当点击被子程序处理(或被父程序捕获)时,键盘不会自动解散。这里是引用的地方。

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

使用react-native中的KeyBoard API就可以了。

import { Keyboard } from 'react-native'

// Hide the keyboard whenever you want using !
Keyboard.dismiss()

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

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

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

为我工作

有几种方法, 如果你像onPress一样控制事件,你可以使用:

import { Keyboard } from 'react-native'

onClickFunction = () => {
     Keyboard.dismiss()
}

如果你想关闭键盘时使用滚动:

<ScrollView keyboardDismissMode={'on-drag'}>
     //content
</ScrollView>

更多的选项是当用户点击键盘外:

<KeyboardAvoidingView behavior='padding' style={{ flex: 1}}>
    //inputs and other content
</KeyboardAvoidingView>