如果我点击文本输入,我希望能够点击其他地方,以便再次关闭键盘(而不是返回键).在我读过的所有教程和博客帖子中,我都没有发现任何与此相关的信息.

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

推荐答案

如果你有keyboardType='numeric'个键盘,键盘不被忽略的问题会变得更严重,因为没有办法忽略它.

用ScrollView替换View不是一个正确的解决方案,就像你有多个textInputbutton,在键盘打开时点击它们只会关闭键盘.

正确的方法是用TouchableWithoutFeedbackKeyboard.dismiss()封装视图

编辑:您现在可以使用ScrollViewkeyboardShouldPersistTaps='handled'来关闭键盘,只有当点击不由子元素们处理时(即点击其他文本输入或按钮)

如果你有

<View style={{flex: 1}}>
    <TextInput keyboardType='numeric'/>
</View>

换成

<ScrollView contentContainerStyle={{flexGrow: 1}}
  keyboardShouldPersistTaps='handled'
>
  <TextInput keyboardType='numeric'/>
</ScrollView>

imp或t {Keyboard} from 'react-native'

<TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
</TouchableWithoutFeedback>

编辑:您还可以创建一个更高阶的组件来关闭键盘.

imp或t React from 'react';
imp或t { TouchableWithoutFeedback, Keyboard, View } from 'react-native';

const DismissKeyboardHOC = (Comp) => {
  return ({ children, ...props }) => (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
      <Comp {...props}>
        {children}
      </Comp>
    </TouchableWithoutFeedback>
  );
};
const DismissKeyboardView = DismissKeyboardHOC(View)

就像这样简单地使用它

...
render() {
    <DismissKeyboardView>
        <TextInput keyboardType='numeric'/>
    </DismissKeyboardView>
}

NOTE: the accessible={false} is required to make the input f或m continue to be accessible through VoiceOver. Visually impaired people will thank you!

Reactjs相关问答推荐

Firebase删除UserWithEmail AndPassword仅创建匿名用户

CreateBrowserRouter将props 传递给父组件以验证权限

滚动事件监听器在Next.js客户端组件中不触发

cypress 不能点击SPAN

如何创建react router v6的自定义子路由?

为什么我的React App.js只在页面刷新时呈现3次?

如何在整个应用程序中显示通用弹出窗口中的点击事件

带有样式的工具提示导致无法向功能组件提供参考警告

在 React 中,如何在指向同一组件的路由中拥有未定义数量的多个动态路径段?

使用获取的数据更新状态,但在try console.log 时它给出未定义

如何更新 FunctionComponentElement 的 props

useState数组不更新

如何在next.js 13中仅在主页导航栏上隐藏组件?

Firebase Storage: 对象不存在图片上传路径错误

React Native应用如何订阅Supabase的实时数据?

改变输入的默认值时出现问题:number react-hook-form

意外的标记.您可能需要一个合适的加载器来处理这种文件类型.书?.img? /*#__PURE__*/React.createElement("img",

map 未显示在react 传单中

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

使用 React、Redux 和 Firebase 的无限循环