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

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

当前回答

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

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

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

其他回答

有几种方法, 如果你像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>

https://facebook.github.io/react-native/docs/keyboard.html

Use

Keyboard.dismiss(0);

隐藏键盘。

我们可以在没有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>
);

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

import {Keyboard} from 'react-native';

使用keyboard .dismiss()隐藏你的键盘在任何onClick或onPress事件。

将TextInput的父组件View包装到一个可压组件中,然后传递Keyboard。解散到onPress道具。因此,如果用户点击TextInput字段之外的任何地方,它将触发键盘。导致TextInput字段失去焦点,键盘被隐藏。

<Pressable onPress={Keyboard.dismiss}>
  <View>
    <TextInput
      multiline={true}
      onChangeText={onChangeText}
      value={text}
      placeholder={...}
     />
   </View>
</Pressable>