如何在内部div元素中启动onClick函数

问题描述 投票:0回答:1

我正在尝试构建一个聊天页面,我可以在其中添加用户,就像在 WhatsApp 中一样,并使每个聊天的每次点击都会根据所选聊天进行响应。

    <div id="list_chat">
      {contacts.map(contact => (
        <ContactBlock
          receiver={contact.receiver}
          username={contact.username}
          displayName={contact.displayName}
          password={contact.password}
          profilePic={contact.profilePic}
          time={contact.time}
          lastmessage={contact.lastmessage}
          key={contact.username}
        />
      ))}
    </div>
function ContactBlock({ receiver, username, displayName, password, profilePic, time, lastmessage}) {
  const handleClick = () => {
    console.log(`Clicked on contact with username:`,);
  };
  return (
    <div className="block" id="contact_block" onClick={handleClick}>
      <div className="imgbx">
        <img src={profilePic} alt="not found" className="cover" />
      </div>
      <div className="details">
        <div className="listhead">
          <h4>{displayName}</h4>
          <p className="time">{time}</p>
        </div>
        <div className="message_p">
          <p>{lastmessage}</p>
        </div>
      </div>
    </div>
  );
}

export default ContactBlock;

我无法激活 ContactBlock 上的 onClick,但它适用于“list_chat”div。 当我单击 ContactBlock 时,它指的是“list_chat”div。

javascript html reactjs node.js onclick
1个回答
1
投票

当您单击

ContactBlock
时,事件可能会传播到 id 为
list_chat
的父级 div。这可能是由于事件捕获所致。

event.stopPropagation()
中添加
handleClick
以防止这种行为。

const handleClick = (event) => {
  event.stopPropagation();
  console.log(`Clicked on contact with username: ${username}`);
};

或者,您可以使用

addEventListener
来指定事件发生时的元素顺序:

访问https://www.w3schools.com/js/tryit.asp?filename=tryjs_addeventlistener_usecapture查看

© www.soinside.com 2019 - 2024. All rights reserved.