React 中实现拖拽功能-插件 react-beautiful-dnd

拖拽功能在平时开发中是很常见的,这篇文章主要使用react-beautiful-dnd插件实现此功能。

非常好用,附上GitHub地址:https://github.com/atlassian/react-beautiful-dnd

安装及引入

复制代码
// 1.引入
# yarn
yarn add react-beautiful-dnd

# npm
npm install react-beautiful-dnd --save

具体使用

复制代码
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// 样式相关 代码
const grid = 8;
// 垂直样式
// const getItemStyle = (isDragging, draggableStyle) => ({
//     // some basic styles to make the items look a bit nicer
//     userSelect: "none",
//     padding: grid * 2,
//     margin: `0 0 ${grid}px 0`,
//
//     // change background colour if dragging
//     background: isDragging ? "lightgreen" : "grey",
//
//     // styles we need to apply on draggables
//     ...draggableStyle
// });
// const getListStyle = isDraggingOver => ({
//     background: isDraggingOver ? "lightblue" : "lightgrey",
//     padding: grid,
//     width: 250,
// });

// 水平样式
const getItemStyle = (isDragging, draggableStyle) => ({
    // some basic styles to make the items look a bit nicer
    userSelect: 'none',
    padding: grid * 2,
    margin: `0 ${grid}px 0 0`,

    // change background colour if dragging
    background: isDragging ? 'lightgreen' : 'grey',

    // styles we need to apply on draggables
    ...draggableStyle,
});
const getListStyle = isDraggingOver => ({
    background: isDraggingOver ? 'lightblue' : 'lightgrey',
    display: 'flex',
    padding: grid,
    overflow: 'auto',
});

class App extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            items: [
                {id: 'item-0', content: 'hello'},
                {id: 'item-1', content: 'I'},
                {id: 'item-2', content: 'am'},
                {id: 'item-3', content: '卡'},
                {id: 'item-4', content: '特'},
                {id: 'item-5', content: '洛'},
            ]
        };
    }

    // a little function to help us with reordering the result
    reOrder = (list, startIndex, endIndex) => {
        const result = Array.from(list);
        const [removed] = result.splice(startIndex, 1);
        result.splice(endIndex, 0, removed);
        return result;
    };

    onDragEnd = (result) => {
        // dropped outside the list
        if (!result.destination) {
            return;
        }

        const items = this.reOrder(
            this.state.items,
            result.source.index,
            result.destination.index
        );

        this.setState({
            items
        });
    }

    render () {
        return (
            <div className="App">
                
                <DragDropContext onDragEnd={this.onDragEnd}>
                    <Droppable droppableId="droppable" direction="horizontal">
                        {(provided, snapshot) => (
                            <div
                                ref={provided.innerRef}
                                style={getListStyle(snapshot.isDraggingOver)}
                                {...provided.droppableProps}
                            >
                                {this.state.items.map((item, index) => (
                                    <Draggable key={item.id} draggableId={item.id} index={index}>
                                        {(provided, snapshot) => (
                                            <div
                                                ref={provided.innerRef}
                                                {...provided.draggableProps}
                                                {...provided.dragHandleProps}
                                                style={getItemStyle(
                                                    snapshot.isDragging,
                                                    provided.draggableProps.style
                                                )}
                                            >
                                                {item.content}
                                            </div>
                                        )}
                                    </Draggable>
                                ))}
                                {provided.placeholder}
                            </div>
                        )}
                    </Droppable>
                </DragDropContext>
                
            </div>
        );
    }
}

export default App;

说明一下:<Droppable />中的 direction 属性可以控制是水平方向还是垂直方向,配合相关 getItemStyle 和 getListStyle 的代码,可做到。
效果展示

补充一下: 如果你是react-creat-app 创建的项目,则需要删除代码里自带的react 严格模式。否则拖拽效果出不来。

相关推荐
自律版Zz3 分钟前
手写 Promise.resolve:从使用场景到实现的完整推导
前端·javascript
梵得儿SHI22 分钟前
Vue 开发环境搭建全指南:从工具准备到项目启动
前端·javascript·vue.js·node.js·pnpm·vue开发环境·nvm版本管理
Glommer42 分钟前
某音 Js 逆向思路
javascript·逆向
街尾杂货店&1 小时前
webpack - 单独打包指定JS文件(因为不确定打出的前端包所访问的后端IP,需要对项目中IP配置文件单独拿出来,方便运维部署的时候对IP做修改)
前端·javascript·webpack
月光技术杂谈1 小时前
用Deepseek 实现一个基于web的扣图应用
前端·javascript·html5·ccs·tensorflow.js·canvas api
kevlin_coder2 小时前
🚀 实现同一个滚动区域包含多个虚拟滚动列表
前端·javascript
金梦人生2 小时前
JS 性能优化
前端·javascript
peachSoda72 小时前
自定义配置小程序tabbar逻辑思路
javascript·vue.js·微信小程序·小程序
hbqjzx2 小时前
记录一个自动学习的脚本开发过程
开发语言·javascript·学习
浪裡遊2 小时前
React开发模式解析:JSX语法与生命周期管理
前端·javascript·react.js·前端框架·ecmascript