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 严格模式。否则拖拽效果出不来。

相关推荐
ZXT3 小时前
js基础重点复习
javascript
言兴3 小时前
秋招面试---性能优化(良子大胃袋)
前端·javascript·面试
WebInfra4 小时前
Rspack 1.5 发布:十大新特性速览
前端·javascript·github
雾恋5 小时前
我用 trae 写了一个菜谱小程序(灶搭子)
前端·javascript·uni-app
烛阴5 小时前
TypeScript 中的 `&` 运算符:从入门、踩坑到最佳实践
前端·javascript·typescript
Java 码农6 小时前
nodejs koa留言板案例开发
前端·javascript·npm·node.js
ZhuAiQuan6 小时前
[electron]开发环境驱动识别失败
前端·javascript·electron
nyf_unknown6 小时前
(vue)将dify和ragflow页面嵌入到vue3项目
前端·javascript·vue.js
胡gh7 小时前
数组开会:splice说它要动刀,map说它只想看看。
javascript·后端·面试
无羡仙7 小时前
React 状态更新:如何避免为嵌套数据写一长串 ...?
前端·react.js