首页 > 解决方案 > 反应由多个组件处理的拖放

问题描述

我正在尝试对我的应用程序使用 react dragtastic 但是当我将一个组件放在一个 Droppable 组件上时,我希望它仅由顶部组件处理,而不是当前位于 WebsiteBody 和 DroppableWrapper 中的 onDrop 函数的所有组件都被调用

这是我的代码 DroppableWrapper 组件

function DroppableWrapper(props) {
  const cards = useCards();
  const setCards = useSetCards();

  function onDrop(droppedCard) {
    const parentCardId = props.parentCard.id;
    for (var index = 0; index < cards.length; ++index) {
      if (cards[index].id === parentCardId) {
        cards[index].children = [...cards[index].children, droppedCard];
      }
      
    }
    setCards([...cards]);

  }

  return (
    <Droppable accepts="card" onDrop={onDrop}>
      {(dragState) => (
        <props.parentCard.component.code.type
          {...props.parentCard.component.code.props}
          {...dragState.events}
        >
          {props.parentCard.component.code.children}
        </props.parentCard.component.code.type>
      )}
    </Droppable>
  );
}

网站正文

function WebsiteBody(props) {
  const cards = useCards();
  const setCards = useSetCards();
  console.log(cards);

  function onDrop(droppedCard) {
    let tempCard = { ...droppedCard };
    if (!tempCard.hasOwnProperty("number")) {
      tempCard.number = 0;
    }

    for (var index = 0; index < cards.length; ++index) {
      if (cards[index].name === tempCard.name) {
        tempCard.number += 1;
        tempCard.name = droppedCard.name + " " + tempCard.number;
      }
    }

    setCards([...cards, tempCard]);
  }

  return (
    <Droppable accepts="card" onDrop={onDrop}>
      {(dragState) => (
        <Box
          w="100vw"
          h="100vh"
          backgroundColor="white"
          display="flex"
          {...dragState.events}
        >
          {cards.map((card) =>
            card.isDroppable ? (
              <DroppableWrapper parentCard={card}></DroppableWrapper>
            ) : (
              card.component.code
            )
          )}
        </Box>
      )}
    </Droppable>
  );
}

当我将卡片放在 DroppableWrapper 上时,两个 onDrop 函数都会被调用,因为两个组件都在彼此之上。怎么做才能只调用 DroppableWrapper onDrop 函数

标签: javascriptreactjsdrag-and-drop

解决方案


推荐阅读