React 漂亮的拖放不适用于 Material UI 组件

React beautiful drag and drop doesn't work with Material UI component

我尝试制作一个可拖动的 MUI 按钮的水平列表react beautiful drag and drop.,但它似乎不起作用。

我用 <DragDropContext><Droppable><Draggable> 标签包裹了我的按钮。 这是代码。

<DragDropContext>
  <Droppable droppableId="characters">
    {(provided, snapshot) => (
    <Stack
      direction="row"
      spacing="{1}"
      className="characters"
      {...provided.droppableProps}
      ref="{provided.innerRef}"
    >
      {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((x, index) => (
      <Draggable key="{x}" draggableId="{x}" index="{index}">
        {(provided, snapshot) => (
        <button
          variant="contained"
          ref="{provided.innerRef}"
          {...provided.draggableProps}
          {...provided.dragHandleProps}
        >
          {x}
        </button>
        )}
      </Draggable>
      ))}
    </Stack>
    )}
  </Droppable>
</DragDropContext>

https://drive.google.com/file/d/1VprPiCk-we5HVhvYzPPBEFdeHMX39BXC/view?usp=sharing

这是我得到的结果。 [不可拖动的按钮列表]

你可以在本期看到,Buttons cannot be used as custom drag handles

所以在你的情况下,你必须在按钮外面放一个 div。而且,draggableId 应该是 string.

<DragDropContext>
  <Droppable droppableId="characters">
    {(provided, snapshot) => (
      <Stack
        direction="row"
        spacing={1}
        className="characters"
        {...provided.droppableProps}
        ref={provided.innerRef}
      >
        {[1, 2, 3, 4, 5, 6, 7, 8].map((x, index) => (
          <Draggable key={x} draggableId={`${x}`} index={index}>
            {(provided, snapshot) => (
              <div
                ref={provided.innerRef}
                {...provided.draggableProps}
                {...provided.dragHandleProps}
              >
                <button variant="contained">{x}</button>
              </div>
            )}
          </Draggable>
        ))}
      </Stack>
    )}
  </Droppable>
</DragDropContext>;