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

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

我对 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>
    }


可排序列表(包装器):

    <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
的文档,但它似乎没有任何效果,也没有警告或错误,文档链接

reactjs react-hooks drag-and-drop dnd-kit
1个回答
9
投票

“Listeners”下的文档中有有关它的信息:

setNodeRef
应该位于父级(整个可拖动元素)中,但
attributes
listeners
应该仅位于按钮道具中。

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

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