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

MUI System Styled组件内部onClick失效问题求助

解决MUI System styled组件内部onClick无法触发的问题

问题描述

使用MUI System的styled创建了InnerContainer组件,但组件内部DeleteIcon的onClick事件无法触发,外层容器的拖拽功能可正常工作。

原因分析

问题出在dnd-kit的{...listeners}上,这个对象包含拖拽所需的onPointerDown等事件监听。当点击DeleteIcon时,事件会冒泡到外层容器,触发拖拽的pointerdown事件,导致内部的onClick事件被中断,无法正常执行。

解决方案

  • 在DeleteIcon(或其父元素)上添加onPointerDown={(e) => e.stopPropagation()},阻止事件冒泡到外层拖拽容器,这样点击删除图标时就不会触发拖拽逻辑,而是正常执行点击事件。
  • 将InnerContainer的定义移到组件外部,避免每次渲染重新创建styled组件,提升性能。

修改后的代码

import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { styled } from "@mui/system";
import DeleteIcon from "@mui/icons-material/Delete";

// 移到组件外部,避免重复创建styled组件
const InnerContainer = styled("div")({
  width: "100%",
  height: "100%",
  display: "flex",
  justifyContent: "space-between",
  alignItems: "end",
  fontWeight: "600",
  "&:hover svg": {
    color: "white",
    transform: "scale(1.3)",
    transition: "0.5s",
  },
  " .inBoxName": {
    marginLeft: "0.5rem",
  },
  " .inBoxTrash": {
    marginRight: "0.5rem",
  },
});

function DraggableBox(props) {
  const { attributes, listeners, setNodeRef, transform, transition } =
    useSortable({ id: props.id });

  const outerContainer = {
    transform: CSS.Transform.toString(transform),
    transition,
    backgroundColor: props.color,
    width: "20%",
    height: "25%",
    display: "inline-block",
  };

  return (
    <div style={outerContainer} ref={setNodeRef} {...attributes} {...listeners}>
      <InnerContainer>
        <div className="inBoxName">{props.name}</div>
        <div className="inBoxTrash">
          <DeleteIcon 
            onClick={() => props.removeColorBox(props.id)}
            onPointerDown={(e) => e.stopPropagation()}
          />
        </div>
      </InnerContainer>
    </div>
  );
}

export default DraggableBox;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:35:19