拖一个svg rect

时间:2017-05-27 17:04:35

标签: javascript html svg

当我尝试像下面一样拖动svg rect时,它首先选择我页面上的任何文本,然后变为可拖动。我最初怎么能让它变得可拖动?

<g
      onDragStart={this.onDragStart}
      onDrag={this.onDrag}
      onDragEnd={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

我正在使用React,这是我的组件的功能:

  onDragStart = (event) => {
    this.setState({
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };

  onDragEnd = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };

1 个答案:

答案 0 :(得分:1)

事实证明,我应该使用onMouseDown,onMouseMove,onMouseOut和onMouseUp事件添加bool属性&#39; active&#39;在组件状态。现在它有效。

<g
  onMouseDown={this.onDragStart}
  onMouseMove={this.onDrag}
  onMouseOut={this.onDrag}
  onMouseUp={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

  onDragStart = (event) => {
    this.setState({
      active: true,
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    if(this.state.active)
      this.setState({
        x: event.clientX - this.state.dx,
        y: event.clientY - this.state.dy
      });
  };

  onDragEnd = (event) => {
    this.setState({
      active: false,
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };