I wrote it because I wanted to use react-dnd, but I can't drag it again after I drag it once.
Could you please take a look at the details?Thank you for your cooperation.The moving objects are placed on the codesandbox.
App.js
import React, {useRef, useState} from "react";
import {DndProvider, useDrag, useDrop} from "react-dnd";
import {HTML5Backend} from "react-dnd-html5-backend";
import "./style.css";
const MovableItem=({setIsFirstColumn,name})=>{
const [{isDragging},drag] = useDrag({
type: "what",
item: {name},
// work when a drug is released
end: (item, monitor) = > {
constdropResult=monitor.getDropResult();
console.log("first", dropResult);
// If you release it on Column 1, Column 1 will enter the name and it will be true.
// otherwise become undefined
if(dropResult&dropResult.name==="Column1"){
console.log("To Column 1";
setIsFirstColumn(true);
} else{
console.log("To Column 2");
setIsFirstColumn(false);
}
},
collect:(monitor)=>({
isDragging —monitor.isDragging()
})
});
constopacity=isDragging?0.4:1;
return(
<div ref={drag}className="movable-item" style={{opacity}}>
We will move this item
</div>
);
};
constColumn=({children,className,title})=>{
const [{canDrop, isOver}, drop] = useDrop({
// Allow what type to be moved to a column
accept: "what",
// Specify where components can be dropped
drop:()=>({name:title}),
collect:(monitor)=>({
isOver:!!monitor.isOver(),
canDrop:!!monitor.canDrop()
})
});
console.log("options", {canDrop, isOver});
return(
<div ref={drop}className={className}>
{title}
{children}
</div>
);
};
export const App=()=>{
const [isFirstColumn, setIsFirstColumn] = useState(true);
const Item=(
<MovableItem setIsFirstColumn={setIsFirstColumn} name={"hello"}/>
);
return(
<div className="container">
<DndProvider backend={HTML5Backend}>
<Column title="Column1" className="column first-column">
{/*If the state is true, pass the component to be dragged*/}
{isFirstColumn & Item}
</Column>
<Column title="Column2" className="column second-column">
{console.log("haha", isFirstColumn)}
{!isFirstColumn&Item}
</Column>
<button
onClick={()=>{
setIsFirstColumn(!isFirstColumn);
}}
>
switchover
</button>
</DndProvider>
</div>
);
};
end: You can't drag
.button
if you want to switch states in
Reference Articles
https://medium.com/litslink/react-dnd-in-examples-ce509b25839d
react-dnd-html5
version was lowered and it worked.15.0.0 to 14.1.0.
react-dnd version 15.0.0 and react-dnd-html5 version 14.1.0 works well.
© 2024 OneMinuteCode. All rights reserved.