You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native:TouchableWithoutFeedback绑定Keyboard.dismiss()无法收起键盘

问题原因与修复方案

核心原因

你写的onPress={Keyboard.dismiss()}是立即执行了Keyboard.dismiss()函数,而非将它作为点击事件的回调传递。这会导致组件渲染时就调用了一次收起键盘的方法,但实际点击TouchableWithoutFeedback区域时,没有绑定任何有效回调逻辑,所以点击外部无法触发收起键盘。

修复步骤

  1. 修正回调写法:把Keyboard.dismiss()改成Keyboard.dismiss(传递函数引用),或者用箭头函数包裹,二选一即可:
// 写法一:直接传递函数引用
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>

// 写法二:箭头函数包裹
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
  1. 额外排查(可选):如果修正后仍无效果,确认以下两点:
    • styles.mainView是否设置了flex: 1,确保它占满整个屏幕,这样点击任意空白区域都能触发事件
    • 没有嵌套的Touchable组件或其他可点击元素拦截了点击事件

修正后的完整代码片段

return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.mainView}>

  <View style={styles.topSearchView}>
    <Image source={require("../../assets/NewSearchIcon.png")} style={styles.searchIcon} />
    <TextInput
      placeholder="Search for food you like..."
      onChangeText={searchedCoursesHandler}
      value={searchedCourses}
      onFocus={() => { setInputBorderOnFocus(true) }}
      style={{
        borderColor: inputBorderOnFocus === true ? "#428463" : "grey",
        borderWidth: 2,
        width: 260,
        height: 50,
        marginLeft: 10,
        fontSize: 18,
        padding: 5,
        borderRadius: 8,
        fontSize: 16
      }}
    />
    <TouchableOpacity
      onPress={() => { setSearchedCourses("") }}
      style={styles.deleteInputTouchable}
    >
      <Image source={require("../../assets/newXicon.png")} style={styles.xButtonIcon} />
    </TouchableOpacity>
  </View>

  <View style={styles.flatListView}>
    <FlatList
      data={searchedCourses}
      renderItem={({ item }) => (
        <TouchableOpacity
          onPress={() => {
            navigation.navigate('item profile', {
              item: item,
            });
          }}
        >
          <View style={styles.flatListItemView}>
            <Image source={{ uri: item.img }} style={styles.flatListImg} />
            <Text>{item.name}</Text>
            <Text>{item.price}$</Text>
          </View>
        </TouchableOpacity>
      )}
      horizontal={true}
    />
  </View>

  {
    searchedCourses.length < 1 &&
    <Image source={require("../../assets/NewPastaImage.png")} style={styles.pastaIcon} />
  }

</View>
</TouchableWithoutFeedback>
);

内容的提问来源于stack exchange,提问作者Cyber

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:11:29