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

这个基本的例子在模拟器中的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仍然会关闭键盘。

其他回答

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

如何在TextInput周围/旁边放置一个可触摸组件?

var INPUTREF = 'MyTextInput';

class TestKb extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <View style={{ flex: 1, flexDirection: 'column', backgroundColor: 'blue' }}>
                <View>
                    <TextInput ref={'MyTextInput'}
                        style={{
                            height: 40,
                            borderWidth: 1,
                            backgroundColor: 'grey'
                        }} ></TextInput>
                </View>
                <TouchableWithoutFeedback onPress={() => this.refs[INPUTREF].blur()}>
                    <View 
                        style={{ 
                            flex: 1, 
                            flexDirection: 'column', 
                            backgroundColor: 'green' 
                        }} 
                    />
                </TouchableWithoutFeedback>
            </View>
        )
    }
}

键盘模块用于控制键盘事件。

import {Keyboard} from 'react-native' 在渲染方法中添加以下代码。 呈现(){ 返回<TextInput onSubmitEditing={键盘。驳回}/ >; }

你可以使用-

Keyboard.dismiss()

解散活动键盘,并根据react本机文档删除焦点。

const dismissKeyboard = require('dismissKeyboard');
dismissKeyboard(); //dismisses it

方法2;

感谢用户@ricardo-stuven指出这一点,还有另一种更好的方法来消除键盘,你可以在react原生文档的例子中看到。

简单地导入键盘并调用它的方法dismiss()

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

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