如何在这个react组件中启用拖拽?

How to Enable Dragging in this react Component?

提问人:gowtham_wick 提问时间:11/11/2023 更新时间:11/11/2023 访问量:15

问:

此代码使用几何图形在页面中绘制一个矩形。Rectangle 将仅使用基本样式属性(如 height、width、left 和 top)生成。拖动未启用。我尝试使用react-draggable库和基本的拖动功能。我想在不弄乱它的尺寸和位置的情况下拖动矩形。我该怎么做?我哪里做错了?

这是我的代码。

import React from 'react';
import Draggable from 'react-draggable';

function Rectangle(props) {
  const { geometry } = props.annotation;
  if (!geometry) return null;

  function onDragStart() {
    console.log("Drag has started");
  }

  function onDragEnd() {
    console.log("Drag has ended");
  }

  return (
    <Draggable
      onStart={onDragStart}
      onEnd={onDragEnd}
      defaultPosition={{
        x: geometry.x,
        y: geometry.y
      }}
    >
      <div  
        style={{ 
          position: 'absolute',
          left: `${geometry.x}%`,
          top: `${geometry.y}%`,
          height: `${geometry.height}%`,
          width: `${geometry.width}%`,
          backgroundColor: 'rgba(128, 0, 0, 0.5)',
          border: '2px dashed red',
          boxSizing: 'border-box',
          transition: 'box-shadow 0.21s ease-in-out',
          cursor: 'move'
        }}
        className={props.className}
      />
    </Draggable>
  );
}

Rectangle.defaultProps = {
  className: '',
  style: {},
};

export default Rectangle;

感谢您的帮助!

提前致谢。

css reactjs draggable data-annotations drag

评论


答: 暂无答案