使用react-beautiful-dnd实现列表间拖拽排序功能

基本概念
DragDropContext:用于包装拖拽根组件,构建一个可以拖拽的范围,Draggable和Droppable都需要包裹在DragDropContext内,不支持嵌套
Droppable:用于包装接收拖拽元素的组件,使被拖动元素可以放置该区域
Draggalbe:用于包装你需要拖动的组件,使组件能够被拖拽

使用方法

1、在项目 package.json 添加相应版本号
        "react-beautiful-dnd": "^10.0.3"

2、把你想能够拖放的代码放到DragDropContext中

import React from 'react';
import {DragDropContext} from 'react-beautiful-dnd';
 
class App extends React.Component {
  //在捕获之前
  onBeforeCapture = () => {
    /*...*/
  };
  //在拖动开始之前
  onBeforeDragStart = () => {
    /*...*/
  };
  //在拖动开始时
  onDragStart = () => {
    /*...*/
  };
  //在拖动变化时
  onDragUpdate = () => {
    /*...*/
  };
  //在拖动结束时
  onDragEnd = result => {
   console.log(result);
  };
 
  render() {
    return (
      <DragDropContext
        onBeforeCapture={this.onBeforeCapture}
        onBeforeDragStart={this.onBeforeDragStart}
        onDragStart={this.onDragStart}
        onDragUpdate={this.onDragUpdate}
        onDragEnd={this.onDragEnd}
      >
        <div>Hello world</div>
      </DragDropContext>
    );
  }
}
export default App;

3、确定可放置区域Dropppable

import React from 'react';
import {DragDropContext,Droppable} from 'react-beautiful-dnd';
 
class App extends React.Component {
  // ...
  getDroppableStyle = snapshot => ({
    //backgroundColor: snapshot.isDraggingOver ? 'blue' : 'grey';
  });
  render() {
    return (
      <DragDropContext
		onBeforeCapture={this.onBeforeCapture}
        onBeforeDragStart={this.onBeforeDragStart}
        onDragStart={this.onDragStart}
        onDragUpdate={this.onDragUpdate}
        onDragEnd={this.onDragEnd}
      >
        <Droppable key = "droppable-1" droppableId="droppable-1" type="PERSON" isDropDisabled = {false}>
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              style={this.getDroppableStyle(snapshot)}
              {...provided.droppableProps}
            >
              <h2>I am a droppable!</h2>
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    );
  }
}
export default App;

droppableId:必要的参数(字符串),用于唯一标识,不要更改此ID,特别是在拖动时
type: 可用于仅接受指定的类。例如:如果您使用type=“person”,那么它将只允许将类型“person”的放到自身上。type=‘task’的将不能被拖放到type为‘person’的上。如果没有提供类型,它将被设置为“DEFAULT”。
direction : 项目流动的方向。选项有 "vertical" (默认)和 "horizontal"。
isDropDisabled:用来确定该区域是否可放置元素,默认为false。true:不可放置,false:可以放置
其下钩子函数参数使用说明:
    provided.innerRef:为了使droppable正确运行,您必须绑定所提供的。innerRef指向ReactElement中尽可能高的DOM节点。这样做是为了避免使用ReactDOM查找DOM节点。
    provided.droppableProps:这是一个包含需要应用于可删除元素的属性的对象。它需要应用到与应用provided.innerRef相同的元素。它目前包含用于样式化和查找的数据属性。
    provided.placeholder: 用于在拖动过程中根据需要在< Droppable />中创建空格。当用户拖动非主列表的列表时,需要此空间。请确保将占位符放在您提供ref的组件中。我们需要增加本身的大小。
    snapshot:当前拖动状态,可以用来在被拖动时改变Droppable的外观,snapshot.isDraggingOver:是否拖动结束

4、在Dropppable区域使用Draggable包裹拖拽元素

import React from 'react';
import {DragDropContext,Droppable,Draggable} from 'react-beautiful-dnd';
 
class App extends React.Component {
  // ...
  
  render() {
    return (
      <DragDropContext
        onBeforeCapture={this.onBeforeCapture}
        onBeforeDragStart={this.onBeforeDragStart}
        onDragStart={this.onDragStart}
        onDragUpdate={this.onDragUpdate}
        onDragEnd={this.onDragEnd}
      >
		 <Droppable key = "droppable-1" droppableId="droppable-1" type="PERSON" isDropDisabled = {false}>
          {(provided, snapshot) => (
            <div
              ref={provided.innerRef}
              style={this.getDroppableStyle(snapshot)}
              {...provided.droppableProps}
            >
               <Draggable key = "draggable-1" draggableId = "draggable-1" index={0} isDragDisabled = {false}>
                {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                    >
                      <h4>My draggable</h4>
                    </div>
                )}
              </Draggable>
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    );
  }
}
export default App;

<Draggable /> 必须始终包含在<Droppable /> 中
droppableId:必要的参数(字符串),用于唯一标识,不要更改此ID特别是在拖动时
index:number类型,必须唯一,必须连续
isDragDisabled:用来确定该元素是否可以被拖动,true:不可拖动,false:可以拖动

5、拖拽结束时,改变源数据

onDragEnd = result => {
  const {source, destination, draggableId} = result;
  //不在拖动范围内则视为没有进行拖动操作
  if (!destination) {
    return;
  }
  //将拖拽元素从源数组中删除,再插入到目标数组中
  // let now_userList = Array.from(this.state.userList);
  // const [removed] = now_userList.splice(source.index,1);
  // now_userList.splice(destination.index,0,removed);
  // //更新数据源
  // this.setState({
  //   userList:now_userList
  // });
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React-beautiful-dnd是一个React组件库,用于实现漂亮且易于使用的拖放列表。要实现一个列表拖放,需要执行以下步骤: 1. 安装react-beautiful-dnd: ``` npm install --save react-beautiful-dnd ``` 2. 导入DragDropContext、Droppable和Draggable组件: ```javascript import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'; ``` 3. 创建状态并为每个列表项目分配一个唯一标识符: ```javascript const [items, setItems] = useState([ { id: "1", content: "Item 1" }, { id: "2", content: "Item 2" }, { id: "3", content: "Item 3" }, { id: "4", content: "Item 4" }, { id: "5", content: "Item 5" }, { id: "6", content: "Item 6" } ]); ``` 4. 创建渲染函数以呈现每个拖动项目: ```javascript const renderItems = () => { return 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> )); }; ``` 5. 创建渲染函数以呈现拖放列表: ```javascript const renderList = () => { return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="items"> {(provided, snapshot) => ( <div {...provided.droppableProps} ref={provided.innerRef} style={getListStyle(snapshot.isDraggingOver)}> {renderItems()} {provided.placeholder} </div> )} </Droppable> </DragDropContext> ); }; ``` 6. 创建onDragEnd函数以处理拖动项目: ```javascript const onDragEnd = result => { if (!result.destination) { return; } const itemsCopy = [...items]; const [reorderedItem] = itemsCopy.splice(result.source.index, 1); itemsCopy.splice(result.destination.index, 0, reorderedItem); setItems(itemsCopy); }; ``` 7. 创建样式函数以获取拖动和放置元素的样式: ```javascript const getItemStyle = (isDragging, draggableStyle) => ({ userSelect: 'none', padding: 16, margin: `0 0 ${8}px 0`, border: isDragging ? '2px solid #000' : 'none', ...draggableStyle }); const getListStyle = isDraggingOver => ({ background: isDraggingOver ? 'lightblue' : '#eee', padding: 8, width: 250 }); ``` 最后,用renderList函数渲染列表,将其放在你的React组件中,就可以开始拖放操作了!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值