这是我的svg代码:
import React from 'react';
import ReactDOM from 'react-dom';
class DragArea extends React.Component {
state = {
viewWidth: 800,
viewHeight: 1000,
gridSize: 40,
vbox: {
x: 0,
y: 0,
w: 800,
h: 1000
},
dragAreaWidth: this.props.width * 40,
dragAreaHeight: this.props.length * 40
}
onmousedown = () => {return false;}
ondragdstart = () => {return false;}
componentDidMount() {
let viewHeight = parseInt(Math.max(window.innerHeight - this.dragAreaLayoutContainer.getBoundingClientRect().top - 50, 400));
let viewWidth = parseInt(Math.max(window.innerWidth - this.dragAreaLayoutContainer.getBoundingClientRect().left - 10, 320));
this.updateSVGDimensions(viewHeight, viewWidth);
}
updateSVGDimensions(viewHeight, viewWidth) {
this.setState({ viewHeight: viewHeight, viewWidth: viewWidth, vbox: Object.assign({}, this.state.vbox , {w: viewWidth, h: viewHeight}) });
}
dragSvg(e) {
console.log(e);
}
render() {
return(
<div ref={(input) => {this.dragAreaLayoutContainer = input}}>
<svg version="1.1" width={this.state.viewWidth} height={this.state.viewHeight} viewBox={Object.values(this.state.vbox).join(" ")} draggable="false" onDragStart={this.ondragdstart} onMouseDown={this.onmousedown} onDrag={this.dragSvg}>
<defs>
<pattern x="0" y="0" width="40" height="40" viewBox="0 0 40 40" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="40" height="40" fill="#dbeef0" stroke="#9bcfd2" strokeWidth="0.4">
</rect>
</pattern>
<pattern x="0" y="0" width="200" height="200" viewBox="0 0 200 200" patternUnits="userSpaceOnUse">
<rect x="0" y="0" width="200" height="200" fill="url(#smallrect)" stroke="#9bcfd2" strokeWidth="1">
</rect>
</pattern>
</defs>
<rect x="0" y="0" width={this.state.dragAreaWidth} height={this.state.dragAreaHeight} fill="url(#bigrect)" id="bg" draggable="false" onDragStart={this.ondragdtart} onMouseDown={this.onmousedown}></rect>
<g></g>
</svg>
</div>
);
}
}
我必须将此svg移入div容器并更新vBox值。我已经尝试过onDrag,onMouseMove和其他一些事件监听器,但它们都没有工作。此外,我必须添加拖放功能到这个svg。这样用户就可以拖动各种图像并放入svg中。用户也可以将丢弃图像从svg的一部分移动到svg的其他部分。我该怎么做才能做出反应。
答案 0 :(得分:1)
SVG不支持拖动事件,因此您需要使用onMouseDown
和onMouseUp
事件,并跟踪isDragging
的状态。
<circle
onMouseDown={handleDragStart}
onMouseUp={handleDragEnd}
/>
简单的示例:https://codepen.io/techniq/pen/yVEeOx?editors=0010
了解更多:http://www.petercollingridge.co.uk/tutorials/svg/interactive/dragging/