[英]drag a div and drop in a container is not happening in react
in drop function data value is getting empty,so how to fix that if I want to drag and drop a div to a particular container.在 drop 函数中,数据值变空了,所以如果我想将 div 拖放到特定容器中,如何解决这个问题。 instead of getting the id its not fetching any value so its throws an error "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"
而不是获取 id 而不是获取任何值,因此它会抛出错误“无法在‘Node’上执行‘appendChild’:参数 1 不是‘Node’类型”
import { useState, useEffect } from "react";
export default function App() {
const [isDown, setIsDown] = useState(false);
const drag = document.querySelector(".drag");
const Onmousedown = () => {
setIsDown(true);
};
const Onmouseup = () => {
setIsDown(true);
};
const Onmousemove = (e) => {
console.log(e.clientX);
if (isDown) {
drag.style.top = e.clientY + "px";
drag.style.left = e.clientX + "px";
}
};
function dragi(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
ev.stopPropagation();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
function onDragOver(e) {
e.preventDefault();
}
return (
<div className="App">
<div
style={{
width: "350px",
height: "70px",
padding: "10px",
border: "1px solid #aaaaaa"
}}
id="div1"
onDrop={(event) => drop(event)}
onDragOver={onDragOver}
></div>
<div
className="drag"
onMouseDown={(e) => Onmousedown(e)}
onMouseUp={(e) => Onmouseup(e)}
onMouseMove={(e) => Onmousemove(e)}
style={{
width: "50px",
height: "50px",
background: "yellow"
}}
draggable="true"
onDragStart={(event) => dragi(event)}
>
Drag
</div>
</div>
);
}
The bug was because you didn't specify id
for the draggable element:该错误是因为您没有为可拖动元素指定
id
:
<div
className="drag"
onMouseDown={(e) => Onmousedown(e)}
onMouseUp={(e) => Onmouseup(e)}
onMouseMove={(e) => Onmousemove(e)}
style={{
width: "50px",
height: "50px",
background: "yellow"
}}
draggable="true"
onDragStart={(event) => dragi(event)}
>
once you add a id
to this element it will work.一旦你向这个元素添加了一个
id
,它就会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.