扫一扫分享
一个拖放库,适用于所有 JavaScript 框架,实现了增强的转换机制来操作 dom 元素。它是迄今为止互联网上唯一一个操纵 DOM 而不是重建它的库。
DFlex 完全用纯 JavaScript/TypeScript 编写,不依赖于任何特定框架。
安装
npm install @dflex/dnd例子
import { store, DnD } from "@dflex/dnd";
const Task = ({ id, task }) => {
  let dndEvent;
  // This reference enable DFlex to move the element when required.
  const ref = react.useRef();
  React.useEffect(() => {
    // Wait until component is mounted to get the reference
    if (ref) {
      store.register({ id, ref: ref.current });
      // All the following inputs work fine:
      // store.register({ ref: ref.current });
      // store.register({ id });
      // store.register({ id, ref: ref.current, depth: 0 });
      // store.register({ id, ref: ref.current, parentID: "my-first-todo" });
    }
  }, [ref]);
  React.useEffect(() => {
    return () => {
      // Clear element from the store when unmounted.
      store.unregister(id);
    };
  }, []);
  const onMouseMove = (e) => {
    if (dndEvent) {
      const { clientX, clientY } = e;
      // Drag when mouse is moving!
      dndEvent.dragAt(clientX, clientY);
    }
  };
  const onMouseUp = () => {
    if (dndEvent) {
      // This is the end of interactive experience.
      dndEvent.endDragging();
      dndEvent = null;
      document.removeEventListener("mouseup", onMouseUp);
      document.removeEventListener("mousemove", onMouseMove);
    }
  };
  const onMouseDown = (e) => {
    const { button, clientX, clientY } = e;
    // Avoid right mouse click and ensure id
    if (typeof button === "number" && button === 0) {
      if (id) {
        // Add event listeners to the entire document.
        // Not just the button boundaries.
        document.addEventListener("mouseup", onMouseUp);
        document.addEventListener("mousemove", onMouseMove);
        // Create DnD instance with no custom options.
        dndEvent = new DnD(id, { x: clientX, y: clientY });
      }
    }
  };
  return (
    <li ref={ref} id={id} onMouseDown={onMouseDown}>
      {task}
    </li>
  );
};
const TodoList = () => {
  React.useEffect(() => {
    return () => {
      // Destroy all elements from the store when unmounted.
      store.destroy();
    };
  }, []);
  const tasks = [
    { id: "mtg", msg: "Meet with Laura" },
    { id: "meetup", msg: "Organize weekly meetup" },
    { id: "gym", msg: "Hit the gym" },
    { id: "proj", msg: "The Rosie Project" },
  ];
  return (
    <ul id="my-first-todo">
      {tasks.map(({ msg, id }) => (
        <Task task={msg} key={id} id={id} />
      ))}
    </ul>
  );
};仅供个人学习参考/导航指引使用,具体请以第三方网站说明为准,本站不提供任何专业建议。如果地址失效或描述有误,请联系站长反馈~感谢您的理解与支持!
手机预览
