React Beautiful DND не работает, элемент нельзя перетаскивать

Я пытался реализовать свой список переупорядочения внутри своей карты с помощью библиотеки react-beautiful-dnd, но я пробовал все аналогичным образом из курсов egghead.io, но не смог заставить его работать. Вот мой код:

    import React, { Component } from "react";
import { Card, Badge } from "react-bootstrap";
import "./projects.scss";
import projectInfo1 from "../../jsonData/projects1";
import { IconContext } from "react-icons";
import { FiPlus } from "react-icons/fi";
import { Droppable, DragDropContext, Draggable } from "react-beautiful-dnd";

class Projects extends Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onDragEnd = this.onDragEnd.bind(this);
    this.onDragStart = this.onDragStart.bind(this);
  }
  onDragEnd = result => {};
  onDragStart = result => {};

  render() {
    return (
      <div className="projectCards">
        {projectInfo1.projectsOrder.map((projectID) => {
          const project = projectInfo1.projects[projectID];
          return (
            <DragDropContext onDragEnd={this.onDragEnd} onDragStart={this.onDragStart}>
            <Card className="projectCard" bg="light" style={{ width: "21rem" }} key={project.id}>
                <Card.Header color="#366FF0" className="projectcardheader">
                  {project.projectName}
                </Card.Header>
                <Droppable droppableId={project.id}>
                  {(provided) => (
                    <div
                      className="cardcontent"
                      innerRef={provided.innerRef}
                      {...provided.droppableProps}
                    >
                      {project.topics.map((j, index) => {
                        return (
                          <Draggable draggableId={j.id} index={index}>
                            {(provided) => (
                              <Card
                                key={j.id}
                                className="topicscard"
                                {...provided.draggableProps}
                                {...provided.dragHandleProps}
                                innerRef={provided.innerRef}
                              >
                                <Card.Title className="topicsheading">
                                  {j.topicName}
                                </Card.Title>
                                <Card.Text className="topicdescription">
                                  {j.topicDescription}
                                </Card.Text>
                                <div>
                                  {j.topicTags ? (
                                    j.topicTags.map((k) => {
                                      return (
                                        <Badge
                                          variant="primary"
                                          className="tags"
                                        >
                                          {k}
                                        </Badge>
                                      );
                                    })
                                  ) : (
                                    <Badge variant="primary"></Badge>
                                  )}
                                </div>
                              </Card>
                            )}

                          </Draggable>
                        );
                      })}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
                <div className="addnewcard">
                  <IconContext.Provider
                    value={{
                      style: { verticalAlign: "middle" },
                      className: "reacticon",
                    }}
                  >
                    <FiPlus />
                  </IconContext.Provider>{" "}
                  Add another discussion
                </div>
            </Card>
            </DragDropContext>
          );
        })}
      </div>
    );
  }
}
export default Projects;

Также я прикрепляю фотографию, на ней просто отображается курсор перетаскивания при наведении курсора на карту, но при перетаскивании ничего не происходит, любая помощь меня спасет!

const projectsInfo1 = {

    projectsOrder:['Project-2','Project-1','Project-5','Project-4','Project-3'],
    projects: {
      'Project-1':{
        projectName: "Project 1",
        id:"p1",
        topics:[{
            id:"p1t1",
            topicName: "Adding a feature: GSoC1",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content.",      
            topicTags:['ReactJs','NodeJS']
        },
        {   id:'p1t2',
            topicName: "Adding a feature: GSoC2",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content.",
            topicTags:['ReactJs','NodeJS']     
        },
        {   id:'p1t3',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content.",
            topicTags:['ReactJs','NodeJS']      
        },
        {   id: 'p1t4',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content.",
            topicTags:['ReactJs','NodeJS']      
        }],
      },
      'Project-2':{
        projectName: "Project 2",
        id:'p2',
        topics:[{
            id:'p2t1',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p2t2',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p2t3',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p2t4',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        }],
      },
      'Project-3':{
        projectName: "Project 3",
        id:'p3',
        topics:[{
            id:'p3t1',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p3t2',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p3t3',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p3t4',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        }],
      },
      'Project-4':{
        projectName: "Project 4",
        id:'p4',
        topics:[{
            id:'p4t1',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p4t2',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p4t3',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p4t4',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        }],
      },
      'Project-5':{
        projectName: "Project 5",
        id:'p5',
        topics:[{
            id:'p5t1',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p5t2',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p5t3',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        },
        {   id:'p5t4',
            topicName: "Adding a feature: GSoC",
            topicDescription: "Some quick example text to build on the card title and make up the bulk of the card's content."      
        }],
      },
    },
  };

  export default projectsInfo1;

person Devansh_Geek    schedule 08.06.2020    source источник


Ответы (1)


ПРИМЕЧАНИЕ.

После беседы в комментарии проблема была с innerRef

<div innerRef={provided.innerRef} to <div ref={provided.innerRef}

В демонстрации они использовали стилизованный компонент, поэтому они используют innerRef, но если вы используете простой div, вам следует использовать только ref


Проблема:

1) он не будет работать автоматически, вам нужно написать для него код при событии завершения перетаскивания onDragEnd

2) Нет управления состоянием, поэтому даже если вы внесете изменения в свой импортированный json, это не отразится, так как у реакции нет идеи повторно отрендерить доменное имя.


Решение:

1) Сохраняйте импортированные данные в state

2) Напишите код внутри onDragEnd, проверьте все условия и примените соответствующие изменения к своему состоянию (не изменяйте состояние, иначе оно не будет отражать изменения)

Примечание. Ниже приведен фрагмент демонстрационного кода из egghead.io для сортировки листинга в той же области, доступной для удаления, просто дайте общее представление о том, как это должно быть.

onDragEnd = result => {
  const { destination, source, draggableId } = result

  if (!destination) {
    return
  }

  if (
    destination.droppableId === source.droppableId &&
    destination.index === source.index
  ) {
    return
  }

  const start = this.state.columns[source.droppableId]
  const finish = this.state.columns[destination.droppableId]


  // this is the logic behind sorting state , you have to do it by your self
  if (start === finish) {
    const newTaskIds = Array.from(start.taskIds)
    newTaskIds.splice(source.index, 1)
    newTaskIds.splice(destination.index, 0, draggableId)

    const newColumn = {
      ...start,
      taskIds: newTaskIds
    }

    const newState = {
      ...this.state,
      columns: {
        ...this.state.columns,
        [newColumn.id]: newColumn
      }
    }

    this.setState(newState)
    return
  }
}

РАБОЧАЯ ДЕМО:

 Редактировать руководство по react-beautiful-dnd

person Vivek Doshi    schedule 08.06.2020
comment
Нет, как в этом видео, вы можете увидеть, яйцеголовый. io / уроки / он работает для него, даже он не написал логику для onDragEnd, то же самое со мной, хотя я написал его вместе с импортированными моими данными в состоянии, все еще без изменений: (/ - person Devansh_Geek; 08.06.2020
comment
Если вы видите видео, элемент можно просто перетаскивать, но он не упорядочивается, как только он отбрасывает элемент, он просто возвращается в исходное положение. - person Vivek Doshi; 08.06.2020
comment
Моя даже не поднимается со своего места. Как будто он не двигается! Он просто показывает значок курсора перетаскивания при наведении - person Devansh_Geek; 08.06.2020
comment
Можно ли поделиться кодом проекта? Или ссылку? Git - person Vivek Doshi; 08.06.2020
comment
Что я должен отправить еще, должен ли я также отправлять свои Исходные данные? Его еще нет на github, поскольку он не работает. Прилагаю и исходные данные. - person Devansh_Geek; 08.06.2020
comment
@Devansh_Geek, попробуйте сменить <div innerRef={provided.innerRef} на <div ref={provided.innerRef} и проверьте еще раз - person Vivek Doshi; 08.06.2020
comment
О, теперь он работает! Большое спасибо, чувак, ты сделал мой день! Я как раз собирался начать изучать руководства по response-dnd и реализовывать это. Спасибо еще раз - person Devansh_Geek; 08.06.2020
comment
Да, даже со стилизованными компонентами, похоже, вы должны использовать ref = {provided.innerRef}. Я потратил кучу времени на это. Я очень хочу, чтобы учебник был обновлен на egghead.io - person Marc; 09.08.2020