React 实现点击拖拽功能onDrag

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
        <style>
            .item {
                border: 1px solid #1da921;
                width: 180px;
                border-radius: 5px;
                box-shadow: 0 0 5px 0 #b3b3b3;
                margin: 5px auto;
                background: #fff;
            }
            .item.active {
                border-style: dashed;
            }
            .item-header {
                font-size: 12px;
                color: #9e9e9e;
                padding: 3px 5px;
            }
            .item-main {
                padding: 5px;
                font-size: 14px;
                color: #424242;
                height: 36px;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
            }
            .item-header-point {
                background: #ccc;
                float: right;
                padding: 0 4px;
                min-width: 10px;
                text-align: center;
                color: #fff;
                border-radius: 50%;
            }
            .col {
                border: 1px solid #d2d2d2;
                flex-grow: 1;
                width: 180px;
                height: 100%;
                margin: 0 2px;
                background: #eee;
                flex-grow: 1;
                display: flex;
                flex-direction: column;
            }
            .col-header {
                height: 40px;
                line-height: 40px;
                background: #1DA921;
                color: #fff;
                text-align: center;
            }
            .col-main {
                overflow: auto;
                flex-grow: 1;
            }
            .col-main.active {
                background: #00ad23;
                opacity: 0.1;
            }
            .task-wrapper {
                display: flex;
                height: 400px;
                width: 700px;
            }
        </style>
    </head>
    <body>
        <div id="app"></div>
        <script type="text/babel">
            const STATUS_TODO = 'STATUS_TODO';
            const STATUS_DOING = 'STATUS_DOING';
            const STATUS_DONE = 'STATUS_DONE';
            
            const STATUS_CODE = {
                STATUS_TODO: '待处理',
                STATUS_DOING: '进行中',
                STATUS_DONE: '已完成'
            }
            let tasks = [{
                id: 0,
                status: STATUS_TODO,
                title: '每周七天阅读五次,每次阅读完要做100字的读书笔记',
                username: '小夏',
                point: 10
            }, {
                id: 1,
                status: STATUS_TODO,
                title: '每周七天健身4次,每次健身时间需要大于20分钟',
                username: '橘子?',
                point: 5
            }, {
                id: 2,
                status: STATUS_TODO,
                title: '单词*100',
                username: '┑( ̄Д  ̄)┍',
                point: 2
            }, {
                id: 3,
                status: STATUS_TODO,
                title: '单词*150',
                username: '┑( ̄Д  ̄)┍',
                point: 2
            }, {
                id: 4,
                status: STATUS_TODO,
                title: '单词*200',
                username: '┑( ̄Д  ̄)┍',
                point: 2
            }, {
                id: 5,
                status: STATUS_TODO,
                title: '单词*250',
                username: '┑( ̄Д  ̄)┍',
                point: 2
            }]
            
            class TaskItem extends React.Component {
                handleDragStart = (e) => {
                    this.props.onDragStart(this.props.id);
                }
                render() {
                    let { id, title, point, username, active, onDragEnd } = this.props;
                    return (
                        <div 
                            onDragStart={this.handleDragStart}
                            onDragEnd={onDragEnd}
                            id={`item-${id}`} 
                            className={'item' + (active ? ' active' : '')}
                            draggable="true"
                        >
                            <header className="item-header">
                                <span className="item-header-username">{username}</span>
                                <span className="item-header-point">{point}</span>
                            </header>
                            <main className="item-main">{title}</main>
                        </div>
                    );
                }
            }
            
            class TaskCol extends React.Component {
                state = {
                    in: false
                }
                handleDragEnter = (e) => {
                    e.preventDefault();
                    if (this.props.canDragIn) {
                        this.setState({
                            in: true
                        })
                    }
                }
                handleDragLeave = (e) => {
                    e.preventDefault();
                    if (this.props.canDragIn) {
                        this.setState({
                            in: false
                        })
                    }
                }
                handleDrop = (e) => {
                    e.preventDefault();
                    this.props.dragTo(this.props.status);
                    this.setState({
                        in: false
                    })
                }
                render() {
                    let { status, children } = this.props;
                    return (
                        <div 
                            id={`col-${status}`} 
                            className={'col'}
                            onDragEnter={this.handleDragEnter}
                            onDragLeave={this.handleDragLeave}
                            onDragOver={this.handleDragEnter}
                            onDrop={this.handleDrop}
                            draggable="true"
                        >
                            <header className="col-header">
                                {STATUS_CODE[status]}
                            </header>
                            <main className={'col-main' + (this.state.in ? ' active' : '')}>
                                {children}
                            </main>
                        </div>
                    );
                }
            }
            
            class App extends React.Component {
                state = {
                    tasks: tasks,
                    activeId: null
                }
                /**
                 * 传入被拖拽任务项的 id
                 */
                onDragStart = (id) => {
                    this.setState({
                        activeId: id
                    })
                }
                
                dragTo = (status) => {
                    let { tasks,  activeId} = this.state;
                    let task = tasks[activeId];
                    if (task.status !== status) {
                        task.status = status;
                        this.setState({
                            tasks: tasks
                        })
                    }
                    this.cancelSelect();
                }
                
                cancelSelect = () => {
                    this.setState({
                        activeId: null
                    })
                }
                
                render() {
                    let { tasks, activeId } = this.state;
                    let { onDragStart, onDragEnd, cancelSelect } = this;
                    return (
                        <div className="task-wrapper">
                            {
                                Object.keys(STATUS_CODE).map(status => 
                                    <TaskCol 
                                        status={status} 
                                        key={status} 
                                        dragTo={this.dragTo}
                                        canDragIn={activeId != null && tasks[activeId].status !== status}>
                                        { tasks.filter(t => t.status === status).map(t => 
                                            <TaskItem
                                                key={t.id}
                                                active={t.id === activeId}
                                                id={t.id}
                                                title={t.title} 
                                                point={t.point} 
                                                username={t.username}
                                                onDragStart={onDragStart}
                                                onDragEnd={cancelSelect}
                                            />)
                                        }
                                    </TaskCol>
                                )
                            }
                        </div>
                    )
                }
            }
            
            ReactDOM.render(
                <App />,
                document.getElementById('app')
            );
        </script>
    </body>
</html>

 

React实现组件拖动功能通常需要结合HTML5的Drag and Drop API以及一些库,比如react-dnd(Drag and Drop for React)。以下是实现步骤的一个大概概述: 1. **安装依赖**:首先,你需要安装`react-dnd`和其他相关的库,例如`react-dnd-html5-backend`,用于处理浏览器的原生拖放支持。 ```bash npm install react-dnd react-dnd-html5-backend ``` 2. **创建DnD组件**:定义一个`Draggable`组件,它将接收一个数据源(通常是state里的某个值),并设置`onDragStart`、`onDrag`和`onDrop`事件处理器,这些处理器会处理开始拖动、移动和释放操作。 ```jsx import { useDrag } from 'react-dnd'; import { HTML5Backend } from 'react-dnd-html5-backend'; function Draggable({ item }) { const [{ isDragging }, drag] = useDrag({ item, collect: (monitor) => ({ isDragging: monitor.isDragging(), }), end: () => { // 需要对结束位置做处理,比如更新状态或触发其他操作 }, }); return ( <div ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}> {item} </div> ); } ``` 3. **添加droppable区域**:创建一个`DropTarget`组件,它监听drop事件,处理被放置的组件。可以使用`useDrop` hook。 ```jsx import { useDrop } from 'react-dnd'; function Droppable({ onDrop }) { const [{ dropResult }, drop] = useDrop({ accept: 'type-of-items', // 匹配Draggables的类型 drop: (item) => { if (dropResult) { onDrop(dropResult.id, item); } }, }); return ( <div ref={drop}> {/* 显示接受区信息 */} </div> ); } ``` 4. **管理状态和组件树**:在应用层面上,你需要维护一个状态来跟踪哪些组件被拖动了,以及它们的新位置。当组件被放置到新的位置时,更新这个状态。 5. **连接所有组件**:在应用程序中,将`Draggable`和`Droppable`组件组合起来,并提供相应的回调函数,如`onDragEnd`和`onDrop`。 ```jsx function App() { // 状态管理... const onDragEnd = (id, newPosition) => {/* 更新状态 */}; return ( <DragDropContext backend={HTML5Backend}> {/* 使用Droppable组件并传入onDrop函数 */} <Droppable onDrop={onDrop}> {/* 渲染Draggable组件及其内容 */} {items.map((item, index) => ( <Draggable key={index} item={item} /> ))} </Droppable> </DragDropContext> ); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值