reactjs 带有拖动手柄的Dnd-kit可排序列表- setActivatorNodeRef无效

6rqinv9w  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(1093)

我有一个dnd-kit库的问题,我试图用拖动手柄激活器实现可排序列表。问题是我不能设置拖动手柄(按钮)为唯一的拖动激活器,而是整个父元素保持活动。
SortableItem组件:

const SortableItem: FunctionComponent<{ id: string }> = (props) => {
      const {
        attributes,
        listeners,
        setNodeRef,
        setActivatorNodeRef,
        transform,
        transition,
      } = useSortable({ id: props.id });

      const context: Context = {
        attributes: attributes,
        listeners: listeners,
        setActivatorNodeRef: setActivatorNodeRef
      }

      return (
        <SortableItemContext.Provider value={context}>
          <div ref={setNodeRef} {...attributes} {...listeners}>
            {props.children}
          </div>
        </SortableItemContext.Provider>
      );
    }

DragHandle组件:

export const DragHandle: FunctionComponent = () => {

      const { attributes, listeners, setActivatorNodeRef } = useContext(SortableItemContext);
      return <button type="button"
                     className="DragHandle"
                     {...attributes} {...listeners}
                     ref={setActivatorNodeRef}>
        <svg viewBox="0 0 20 20" width="12">
          <path d="cleaned..."></path>
        </svg>
      </button>
    }

排序列表( Package ):

<DndContext collisionDetection={closestCenter}
                modifiers={[restrictToVerticalAxis, restrictToWindowEdges]}
                onDragEnd={onSortEnd}>

      <SortableContext items={ids}
        strategy={verticalListSortingStrategy}>

        { props.data.map((item, itemKey) => (
          <SortableItem id={item[props.idKeyName]}
                        key={`si-${item[props.idKeyName]}`}>
            { props.mapFunction(item, itemKey) }
          </SortableItem>
        ))}
  
      </SortableContext>

    </DndContext>

用法:

<SortableList onSortEnd={onSortEnd}
            idKeyName={'id'}
            data={data}
            mapFunction={(item: ICreateQuestionAnswer, itemKey: number) => <div>
                <DragHandle />
                -----
              </div>
            } />

我遵循了关于setActivatorNodeRef的文档,但它似乎没有效果,也没有警告或错误,文档链接

inn6fuwd

inn6fuwd1#

在“监听器”下的文档中有关于它的信息:
“setNodeRef”应位于父级(可拖动的整个元素)中,但“attributes”和“listener”应仅位于按钮属性中。

import {useDraggable} from '@dnd-kit/core';

function Draggable() {
  const {attributes, listeners, setNodeRef} = useDraggable({
    id: 'unique-id',
  });
  
  return (
    <div ref={setNodeRef}>

      /* Some other content that does not activate dragging */

      <button {...listeners} {...attributes}>Drag handle</button>
    </div>
  );
}

https://docs.dndkit.com/api-documentation/draggable/usedraggable

相关问题