如何在使用 React Beautiful DnD 的情況下在 React 中新增拖放功能


在本文中,我們將瞭解如何在列表中拖放元素。當你製作聊天、約會、信使或其他類似型別的網路應用時,拖放功能會非常有用。

示例

首先安裝包 "react-beautiful-dnd"

npm i --save react-beautiful-dnd

這個庫將用於在一個列表內新增可拖放元素。

App.js 中新增以下程式碼行 −

import { DragDropContext, Droppable, Draggable } from "reactbeautiful-dnd";
import React, { useState } from "react";
import "./App.css";

const finalSpaceCharacters = [
   {
      id: "gary",
      name: "Gary Goodspeed",
   },
   {
      id: "cato",
      name: "Little Cato",
   },
   {
      id: "kvn",
      name: "KVN",
   },
   {
      id: "mooncake",
      name: "Mooncake",
   },
   {
      id: "quinn",
      name: "Quinn Ergon",
   },
];

export default function App() {
   const [characters, updateCharacters] = useState(finalSpaceCharacters);
   function handleOnDragEnd(result) {
      if (!result.destination) return;

      const items = Array.from(characters);
      const [reorderedItem] = items.splice(result.source.index, 1);
      items.splice(result.destination.index, 0, reorderedItem);

      updateCharacters(items);
   }
   return (
      <div className="App">
      <header className="App-header">
         <h1>Final Space Characters</h1>
         <DragDropContext onDragEnd={handleOnDragEnd}>
            <Droppable droppableId="characters">
            {(provided) => (
               <ul className="characters"{...provided.droppableProps}ref={provided.innerRef}>
               {characters.map(({ id, name }, index) => {
                  return (
                     <Draggable key={id} draggableId={id}index={index}>{(provided) => (<liref{provided.innerRef}{...provided.draggableProps}{...provided.dragHandleProps}>
                        <div className="charactersthumb"></div>
                        <p>{name}</p>
                        </li>
                     )}
                     </Draggable>
                  );
               })}
               {provided.placeholder}
               </ul>
            )}
            </Droppable>
         </DragDropContext>
      </header>
   </div>
   );
}

在這裡我們使整個 <ul> 列表可拖放(無論在可拖放還是可放置的情況下,"provided" 都是必需的)。

在可放置的 <ul> 中,我們映射了整個角色列表,並使每個元素可拖放。在每個元件中,我們添加了包含所有資料的 <li>。我們在 <li> 上使用了每個可拖放元件的引用。

接下來,在 App.css 中新增以下程式碼行,以建立網站的基本 CSS −

.characters {
   list-style: none;
   padding-left: 0;
}

.characters li {
   display: flex;
   align-items: center;
   border: solid 2px #d0d0d0;
   border-radius: .2em;
   padding: .5em .8em .5em .5em;
   margin-bottom: 1em;
}

.characters p {
   max-width: none;
   font-weight: bold;
   margin: 0;
}

.characters-thumb {
   overflow: hidden;
   flex-shrink: 0;
   width: 2em;
   height: 2em;
   background-color: #e8e8e8;
   padding: .5em;
   margin-right: .5em;
}
.characters-thumb img {
   display: block;
   width: 100%;
   height: auto;
}

輸出

在執行時,它將產生以下輸出 −

更新於:28-9-2021

885 次瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.