1. 程式人生 > 程式設計 >react-beautiful-dnd 實現元件拖拽功能

react-beautiful-dnd 實現元件拖拽功能

目錄
  • 1.安裝
  • 2.APi
  • 3.react-beautiful-dnd demo
    • 3.1 demo1 縱向元件拖拽
    • 3.2 demo2 水平拖拽
    • 3.3 demo3實現一個代辦事項的拖拽(縱向 橫向拖拽)
  • 4.感受

    一個React. 的 漂亮,可移植性 列表拖拽庫。想了解更多react-beautiful-dnd特點適用人群請看官方文件、中文翻譯文件

    npm:https://www.npmjs.com/package/react-beautiful-dnd

    1.安裝

    ​ 在已有react專案中 執行以下命令 so easy。

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

    2.APi

    詳情檢視 官方文件。

    3.react-beautiful-dnd demo

    3.1 demo1 縱向元件拖拽

    效果下圖:

    react-beautiful-dnd 實現元件拖拽功能

    demo1.gif

    實現程式碼:

    import React,{ Component } from "react";
    import { DragDropContext,Droppable,Draggable } from "react-beautiful-dnd";
     
    //初始化資料
    const getItems = count =>
      Array.from({ length: count },(v,k) => k).map(k => ({
        id: `item-${k + 1}`,content: `this is content ${k + 1}`
      }));
     
    // 重新記錄陣列順序
    const reorder = (list,startIndex,endIndex) => {
      const result = Array.from(list);
     
      const [removed] = result.splice(startIndex,1);
     
      result.splice(endIndex,removed);
      return result;
    };
     
    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`,// 拖拽的時候背景變化
      background: isDragging ? "lightgreen" : "#ffffff",// styles we need to apply on draggables
      ...draggableStyle
    });
     
    const getListStyle = () => ({
      background: 'black',padding: grid,width: 250
    });
     
     
     
    export default class ReactBeautifulDnd extends Component {
      constructor(props) {
        super(props);
        this.state = {
          items: getItems(11)
        };
        this.onDragEnd = this.onDragEnd.bind(this);
      }
     
      onDragEnd(result) {
        if (!result.destination) {
          return;
        }
     
        const items = reorder(
          this.state.items,result.source.index,result.destination.index
        );
     
        this.setState({
          items
        });
      }
     
     
      render() {
        return (
          <DragDropContext onDragEnd={this.onDragEnd}>
            <center>
              <Droppable droppableId="droppable">
                {(provided,snapshot) => (
                  <div
                  //provided.droppableProps應用的相同元素.
                    {...provided.droppableProps}
                    // 為了使 droppable 能夠正常工作必須 繫結到最高可能的DOM節點中provided.innerRef.
                    ref={prov
    ided.innerRef} style={getListStyle(snapshot)} > {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={getIHlMeraaab
    temStyle( snapshot.isDragging,provided.draggableProps.style )} > {item.content} </div> )} </Draggable> ))} {provided.placeholder} </div> )} </Droppable> </center> </DragDropContext> ); } }

    3.2 demo2 水平拖拽

    ​ 效果下圖:

    react-beautiful-dnd 實現元件拖拽功能

    demo2.gif

    實現程式碼: 其實和縱向拖拽差不多 Droppable 中 多添加了一個排列順序的屬性,direction="horizontal"

    import React,Draggable } from "react-beautiful-dnd";
     
     
    const getItems = count => (
      Array.from({ length: count },content: `this is content ${k + 1}`
      }))
    )
     
    // 重新記錄陣列順序
    const reorder = (list,endIndex) => {
      const result = Array.from(list);
      //刪除並記錄 刪除元素
      const [removed] = result.splice(startIndex,1);
      //將原來的元素新增進陣列
      result.splice(endIndex,removed);
      return result;
    };
     
    const grid = 8;
     
     
    // 設定樣式
    const getItemStyle = (isDragging,margin: `0 ${grid}px 0 0 `,// styles we need to apply on draggables
      ...draggableStyle
    });
     
    const getListStyle = () => ({
      background: 'black',display: 'flex',overflow: 'auto',});
     
     
    class ReactBeautifulDndHorizontal extends Component {
      constructor(props) {
        super(props);
        this.state = {
          items: getItems(10)
        };
        this.onDragEnd = this.onDragEnd.bind(this);
      }
     
      onDragEnd(result) {
        if www.cppcns.com(!result.destination) {
          return;
        }
     
        const items = reorder(
          this.state.items,result.destination.index
        );
     
        this.setState({
          items
        });
      }
     
      render() {
        return (
          <DragDropContext onDragEnd={this.onDragEnd}>
            <Droppable droppableId="droppable" direction="horizontal">
              {(provided,snapshot) => (
                <div
                  {...provided.droppableProps}
                  ref={provided.innerRef}
                  style={getListStyle(snapshot.isDraggingOver)}
                >
                  {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>
        )
      }
    }
     
    export default ReactBeautifulDndHorizontal

    3.3 demo3實現一個代辦事項的拖拽(縱向 橫向拖拽)

    react-beautiful-dnd 實現元件拖拽功能

    demo3.gif

    實現原理其實大同小異 。程式碼整理後放在上。地址:github

    4.感受

    目前簡單的使用react - beautiful-dnd下來感覺 ,上手感覺挺簡單,api也不繁瑣。效能也不錯(demo2中做過渲染170多個task。拖拽起來還是如絲般順滑)。日後遇到啥不足會mark在一下。

    到此這篇關於react-beautiful-dnd 實現元件拖拽的文章就介紹到這了,更多相關react-beautiful-dnd 元件拖拽內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!