如何使用 React 停止拖动时恢复可拖动组合的位置



我有一个Draggable组件,里面有一个容器。 我希望在停止拖动时重置Draggable的位置(onStop(。 这是我Draggable的属性:

<Draggable
axis="x"
bounds={{top: 0, bottom: 0, left: -75, right: 0}}
onStop={//what to do here}
>

我该怎么做?

所以,我研究了,你可以用position={{x: 0, y: 0}}来让它工作。

创建位置状态

const [pos, setPos] = useState({x:0, y:0});

使用onDrag设置可拖动组件移动时的位置状态

const [pos, setPos] = useState({x:0, y:0});
const handleDrag = (e, data)=>{
setPos({x:data.x, y:data.y});
}
<Draggable onDrag={(e, data) => handleDrag(e, data)}/>

使用onStop拖动结束时将位置设置回 0

const [pos, setPos] = useState({x:0, y:0});
const handleDrag=(e, data)=>{
setPos({x:data.x, y:data.y});
}
const handleDragStop=()=>{
setPos({x:0, y:0});
}
<Draggable onDrag={(e, data) => handleDrag(e, data)} 
onStop={handleDragStop}/>

使用position将可拖动组件的位置设置为状态

const [pos, setPos] = useState({x:0, y:0});
const handleDrag=(e, data)=>{
setPos({x:data.x, y:data.y});
}
const handleDragStop=()=>{
setPos({x:0, y:0});
}
<Draggable onDrag={(e, data) => handleDrag(e, data)} 
onStop={handleDragStop} 
position={pos}/>

最新更新