You need to enable JavaScript to run this app. React Native onItemClick绑定函数未触发无console日志输出问题
优惠活动
大模型
产品
解决方案
定价
更多

React Native onItemClick绑定函数未触发无console日志输出问题

React Native 点击事件不触发修复方案

核心问题点

  • 事件名使用错误:React Native 内置的TouchableOpacity组件没有onItemClick点击事件,正确的触发点击的属性是onPress
  • 函数式组件错误使用this关键字:你当前编写的是函数式组件,不存在类组件的this指向,this.xxxHandle的写法无法访问到你定义的处理函数,会返回undefined
  • 处理函数未正确声明:viewHandle、editHandle、deleteHandle定义时缺少const关键字,属于非法的隐式全局变量赋值,严格模式下会直接报错
  • 未传递参数:你的处理函数需要接收item参数,绑定事件时需要通过箭头函数包裹传入对应值

修正后代码示例

首先修正处理函数的声明:

// 加上const关键字正确声明函数
const viewHandle = (item) => {
  console.log('click on view id', item)
}

const editHandle = (item) => {
  console.log('click on edit id', item)
}

const deleteHandle = (item) => {
  console.log('click on delete id', item)
}

然后修正rightSwipe函数,需要从上层列表渲染项把item传入,绑定事件替换为onPress、删除this:

// rightSwipe接收item参数,从渲染Swipeable的renderItem里传进来
const rightSwipe = (item) => (progress, dragX) => {
  const scale = dragX.interpolate({
    inputRange: [1, 270],
    outputRange: [0, -1],
  });
  return (
    <>
      <TouchableOpacity activeOpacity={0.3} onPress={() => deleteHandle(item)}>
        <View style={styles.deleteBox}>
          <Animated.Text style={{ transform: [{scale: scale}]}}>
            <MaterialIcons name="delete" size={37} color="red" />
          </Animated.Text>
        </View>
      </TouchableOpacity>

      <TouchableOpacity activeOpacity={0.3} onPress={() => editHandle(item)}>
        <View style={styles.editBox}>
          <Animated.Text style={{ transform: [{scale: scale}]}}>
            <MaterialIcons name="edit" size={37} color="grey" />
          </Animated.Text>
        </View>
      </TouchableOpacity>
      
      <TouchableOpacity activeOpacity={0.3} onPress={() => viewHandle(item)}>
        <View style={styles.viewBox}>
          <Animated.Text style={{ transform: [{scale: scale}]}}>
            <MaterialIcons name="preview" size={37} color="grey" />
          </Animated.Text>
        </View>
      </TouchableOpacity>
    </>
  )    
}

最后在FlatList的renderItem里渲染Swipeable时,调用renderRightActions传入item即可:

renderItem={({item}) => {
  return (
    <Swipeable renderRightActions={rightSwipe(item)}>
      {/* 你的列表项原有内容 */}
    </Swipeable>
  )
}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 09:36:05