React.js - setDragImage on draggable element

时间:2017-07-12 08:21:31

标签: javascript node.js html5 reactjs draggable

I'm trying to swap out the default image that the browser uses when I drag a draggable element (in this case the ul below). Here is my code. I'm not getting any errors - it just doesn't work, and I'm left with the default image used by the browser.

drag(e) {
  let img = new Image()
  img.src = 'https://some-image.png'
  e.dataTransfer.setDragImage(img, 0, 0)
}

render() {
  return(
    <ul draggable="true" onDrag={(e) => {this.drag(e)}>
      <li>1</li>
      <li>2</li>
    </ul>
  )
}

1 个答案:

答案 0 :(得分:1)

致电setDragImage()时,图片尚未加载。我通过在mount上创建图像并将其存储在状态:

来处理此问题
 componentDidMount() {
    const img = new Image();
    img.src = 'https://some-image.png';
    img.onload = () => this.setState({ dragImg: img });
 }
 drag(e) {
    e.dataTransfer.setDragImage(this.state.dragImg, 0, 0);
 }