react 拖拽连接插件_在 React 中实现拖拽功能-使用插件 react-beautiful-dnd

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

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

react-beautiful-dnd.png

废话不多说,上代码。

安装及引入

// 1.引入

# yarn

yarn add react-beautiful-dnd

# npm

npm install react-beautiful-dnd --save

// 2.使用

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 (

{(provided, snapshot) => (

ref={provided.innerRef}

style={getListStyle(snapshot.isDraggingOver)}

{...provided.droppableProps}

>

{this.state.items.map((item, index) => (

{(provided, snapshot) => (

ref={provided.innerRef}

{...provided.draggableProps}

{...provided.dragHandleProps}

style={getItemStyle(

snapshot.isDragging,

provided.draggableProps.style

)}

>

{item.content}

)}

))}

{provided.placeholder}

)}

);

}

}

export default App;

注意,

中的 direction 属性可以控制是水平方向还是垂直方向,配合相关 getItemStyle 和 getListStyle 的代码,可做到。

最后,效果展示

react-beautiful-dnd-demo.gif

你可能感兴趣的:(react,拖拽连接插件)