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

React中map函数内元素onClick函数失效问题求助

解决WhatsApp克隆中点击头像无法打印用户ID的问题

你的代码里有两个关键问题导致点击事件失效:

1. onClick 事件绑定错误

你当前写的 onClick={seeMsg(currUser.id)} 会在组件渲染阶段就立即执行seeMsg函数,而不是等到点击头像时才触发。正确的做法是传递一个函数引用,确保只有点击时才执行逻辑,改成箭头函数包裹即可:

onClick={() => seeMsg(currUser.id)}

2. 无效的数组解构

代码中的 const [name, id, time, image] = user; 完全错误:user 是整个用户数组,不是单个用户对象,这行代码不仅毫无作用,还会导致变量值混乱,直接删除即可。


修正后的完整代码

import React from 'react'
import user from './api/Userdata'
const Chats = () => {
  const seeMsg = (id) => {
    console.log(id)
  }
  return (
    <div className="main">
        { user.map((currUser) =>{
        return(
        <div className="user w-full h-14 my-1 flex justify-between content-center" key={currUser.id}>
            <img className='shadow rounded-full max-w-full h-11 w-11 align-middle border-none' src={currUser.image} onClick={() => seeMsg(currUser.id)} alt={currUser.name}/>
            <div className="name pr-16 pl-1 justify-center text-center flex items-center text-gray-900 font-medium mb-1">{currUser.name}</div>
            <div className="time font-thin text-xs text-center flex items-center pr-2">{ currUser.time }</div>
        </div>
          )})}
      </div>
  )
}

export default Chats

额外优化:给img标签添加了有意义的alt文本alt={currUser.name},提升页面可访问性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:46:05