dragula在react中的使用

参考文档:官方文档

使用步骤

  1. yarn add dragula
  2. 引入dragula的样式

效果预览

最终效果预览

代码

App.js

import React, {   useState, useEffect  } from 'react';
import './App.scss';
import dragula  from 'dragula'
function App() {

    const [data1, setData1] = useState([{id:0,name:'box1-1'}, {id:1, name:'box1-2'}])
    const [data2, setData2] = useState([{id:0,name:'box2-1'}, {id:1, name:'box2-2'}])

    useEffect(()=>{
        let drake = dragula([document.querySelector('.left_comp'), document.querySelector('.right_comp')],{
        moves: function (el, source, handle, sibling) { // 设置className === 'handle_box'的可以拖拽
            return handle.className === 'handle_box';
        },
        accepts: (el, target) => { // 设置可拖拽进入的目标区域
            return target.className === 'right_comp'
        },
        copy: (el, source) => { // 是否可复制
            return source.className === 'left_comp'
        },
        })
        drake.on('drop', (el, target, source, sibling) => { // 做事件监听

        })
        
        return () =>{

        }
    })
  
    
    let leftComp = (
        <div className='left_comp'>
        {data1 && data1.map(item =>{
            return(
            <div key={item.id} data-id={item.id} className='handle_box' >{item.name}</div>
            )
        })}
        </div>
    ) 
    let rightComp = (
        <div className='right_comp' id='right_parent'>
        {data2 && data2.map(item =>{
            return(
            <div key={item.id} data-id={item.id} className='box'>{item.name}</div>
            )
        })}
        </div>
    ) 
    return (
        <div className="App">
            <div className="left">
                {leftComp}
            </div>
            <div className="right">
                {rightComp}
            </div>
        </div>
    )
    }
    export default App;

app.scss

.App{
  height: 100vh;
  position: relative;
}
.left{
  width: 50%;
  height: 100%;
  border-right: 1px solid blue;
  position: absolute;
  left: 0;
  top: 0;
}
.left_comp, .right_comp{
  height: 100%;
}
.right{
  width: 50%;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
}
.box, .handle_box{
  border: 1px solid skyblue;
  width: 60px;
  height: 50px;
  margin: 5px;
}
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐