Реагирующий перетаскиваемый и сортируемый компонент

#reactjs #sorting #drag-and-drop

#reactjs #сортировка #перетаскивание

Вопрос:

Я пытаюсь создать выпадающую зону для добавления изображений в мое приложение. Я также хочу, чтобы эти изображения после добавления можно было сортировать, перетаскивая их и переупорядочивая в зоне типа сетки.

Я реализовал компонент react-dropzone-component, который великолепен. Теперь проблема заключается в том, чтобы иметь возможность выбирать изображения, добавленные в dropzone, и перетаскивать их, чтобы изменить их порядок по желанию.

 return (
      <Reorder
        reorderId="my-list" // Unique ID that is used internally to track this list (required)
        reorderGroup="reorder-group" // A group ID that allows items to be dragged between lists of the same group (optional)
        // getRef={this.storeRef.bind(this)} // Function that is passed a reference to the root node when mounted (optional)
        component="div" // Tag name or Component to be used for the wrapping element (optional), defaults to 'div'
        placeholderClassName="placeholder" // Class name to be applied to placeholder elements (optional), defaults to 'placeholder'
        draggedClassName="dragged" // Class name to be applied to dragged elements (optional), defaults to 'dragged'
        // lock="horizontal" // Lock the dragging direction (optional): vertical, horizontal (do not use with groups)
        holdTime={500} // Default hold time before dragging begins (mouse amp; touch) (optional), defaults to 0
        touchHoldTime={500} // Hold time before dragging begins on touch devices (optional), defaults to holdTime
        mouseHoldTime={0} // Hold time before dragging begins with mouse (optional), defaults to holdTime
        onReorder={this.onReorder.bind(this)} // Callback when an item is dropped (you will need this to update your state)
        autoScroll={true} // Enable auto-scrolling when the pointer is close to the edge of the Reorder component (optional), defaults to true
        disabled={false} // Disable reordering (optional), defaults to false
        disableContextMenus={true} // Disable context menus when holding on touch devices (optional), defaults to true
        placeholder={
          <div className="custom-placeholder" /> // Custom placeholder element (optional), defaults to clone of dragged element
        }
      >
        <DropzoneComponent
          config={config}
          eventHandlers={eventHandlers}
          djsConfig={djsConfig}
        />

      </Reorder>
 

Есть несколько отличных компонентов, называемых react-sortable-hoc или react-reorder, но я не могу его интегрировать, поскольку этот компонент должен иметь доступ к любому отдельному изображению, добавленному во время. У меня есть доступ только к более высокому компоненту Dropzone, но не к его дочерним элементам.

Кому-нибудь удалось добиться этого каким-либо другим способом? введите описание изображения здесь

Ответ №1:

Не уверен, что вам это понадобится сейчас или нет. Я наткнулся на этот точный вариант использования и использовал react-drag-sortable (https://www.npmjs.com/package/react-drag-sortable ) для сортировки с помощью перетаскивания в react-dropzone

 //import component
import DragSortableList from 'react-drag-sortable';

//function to be called in every sort
onSort = (sortedList,dropEvent) => {
// arrange items according to events
let _sortedList = []
for (let i = 0; i<sortedList.length ; i  ) {
  _sortedList.push(
    images.find((item)=>{
      if (item.key === sortedList[i].content.key) {
        item['sort'] = i 1;
        return item;
      }
    })
  )
}
this.setState({sortedList: [..._sortedList]})
};

// component
 <Dropzone
      ref={node => {
        this.dropzoneRef = node;
     }}
     onDrop={this.onDrop}
 >
  <DragSortableList
    items={this.state.sortedList}
    dropBackTransitionDuration={0.3}
    onSort={onSort}
    placeholder: <div className={`placeholderContent`}>DROP HERE</div>
    type: 'grid'
  />
 </Dropzone>