一、准备项目
我们按常规,使用 create-react-app 这个工具来创建项目。如果你本地没有安装 npx 的话,强烈推荐,使用非常方便。
1.npx create-react-app react-draggalbe-tutorial
2.cd react-draggalbe-tutorial
3.npm start
在准备好 react 脚手架后,你就可以到目录里,执行 npm start把项目跑起来。
二、安装 react-draggable
现在执行 npm install react-draggable,执行完后应该在你的 node_modules 中就装好了 react-draggable。
三、接入 react-draggable
现在,我们希望当用户鼠标拖拽把手时,把手本身可以被移动。首先我们把 react-draggable 导入
import React, { useState, useRef } from 'react';
import './App.css';
import Draggable from 'react-draggable'; // The default
function index() {
const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
const draggleRef = useRef<HTMLDivElement>(null);
const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
const { clientWidth, clientHeight } = window.document.documentElement;
const targetRect = draggleRef.current?.getBoundingClientRect();
if (!targetRect) {
return;
}
setBounds({
left: -targetRect.left + uiData.x,
right: clientWidth - (targetRect.right - uiData.x),
top: -targetRect.top + uiData.y,
bottom: clientHeight - (targetRect.bottom - uiData.y),
});
};
return (
<div className="App">
{/* handle这个属性的作用就是用来选出对拖动有反应的组件部分。我们只希望在用户拖动把手时,整个组件移动。所以我们只需要用 handle 属性,选出来把手即可 */}
{/* bounds 属性限制可以拖动的范围 */}
<Draggable handle='.drag-handler' bounds={bounds}
onStart={(event, uiData) => onStart(event, uiData)}>
<div ref={draggleRef} className="box">
<div className='drag-handler'>拖这里可以</div>
<div>box 正文,拖这里拖不动</div>
</div>
</Draggable>
</div>
);
}
export default index;
四、App.css
App.css中代码
.box {
background-color: green;
width: 300px;
height: 300px;
display: flex;
flex-direction: column;
}
.drag-handler {
background-color: grey;
height: 50px;
cursor: move;
}