虽然现在html5已经有支持拖拽的事件,但是支持还不那么全面。所以目前大部分的拖拽还是通过原生的鼠标事件来实现列表重新排序。话不多说。一步步开始做吧。下标index: x是为了方便理解添加的。
目录
Step1.准备一个模拟数据
let list = [];
for(let i = 0; i< 10; i++){
list.push(`item ${
i}`);
}
Step2.渲染到页面上
export default class DragAndDrop extends Component {
constructor() {
super();
this.state = {
lists: list
}
}
render(){
return(
<div className='listContainer'>
{
this.state.lists.map((item, index) => (
<li key={
item}>{
item} <span>index: {
index}</span></li>
))}
</div>
)
}
}
Step3.写样式
.listContainer {
position: relative;
width: 350px;
margin: 10px 0 0 40px;
background-color: #eee; /*跟item移动时候的背景颜色一样,就可以产生一种移开后还留有阴影的错觉*/
}
.listContainer li {
list-style: none;
border-bottom: 1px solid #9c9c9c;
padding: 10px;
background-color: #fff;
}
.listContainer li span{
font-size: 10px;
}
.listContainer .coverMask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.1);
}
Step4.添加mouseDown事件,添加一个遮盖层,绑定mouseMove, mouseUp事件
constructor() {
super();
this.state = {
lists: list,
dragging: false,
draggingItemIndex: -1,
startPageY: 0,
offsetY: 0
}
}
handleMouseDown = (event, index) => {
this.setState({
dragging: true,
draggingItemIndex: index,
startPageY: event.pageY
})
}
handleMouseUp = (event) => {
this.setState({
dragging: false,
draggingItemIndex: -1