使用挂钩将基于React类的组件转换为React功能组件

时间:2019-07-31 16:25:42

标签: javascript reactjs drag-and-drop react-hooks

我已经使用React Class Base方法开发了像扑克之类的游戏,现在我想将其转换为使用挂钩的React功能组件,但不知道如何...

    this is my initial data




    const initialData = {
        tasks: {
          'task-1': { id: 'task-1', content: 'Ace'},
          'task-2': { id: 'task-2', content: 'King' },
          'task-3': { id: 'task-3', content: 'Queen' },
          'task-4': { id: 'task-4', content: 'Jack' },
          'task-5': { id: 'task-5', content: 'two' },
          'task-6': { id: 'task-6', content: 'three' },
          'task-7': { id: 'task-7', content: 'four' },
          'task-8': { id: 'task-8', content: 'five' },
          'task-9': { id: 'task-9', content: 'six' },
          'task-10': { id: 'task-10', content: 'seven' },
          'task-11': { id: 'task-11', content: 'eight' },
          'task-12': { id: 'task-12', content: 'nine' },
          'task-13': { id: 'task-13', content: 'ten' }
        },

        columns: {
          'column-1': {
            id: 'column-1',
            title: 'Cards',
            taskIds: ['task-1', 'task-2', 'task-3', 'task-4','task-5','task-6','task-7','task-8','task-9','task-10','task-11','task-12','task-13']
          },
          'column-2': {
            id: 'column-2',
            title: 'Drop Your Card Here',
            taskIds: []
          },

        },
        // Facilitate reordering of the columns
        columnOrder: ['column-1', 'column-2']
      }


      export default initialData


     index.js component 

在本节中,本节将如何转换为功能组件
我想在这里使用钩子将状态用于状态

    import React from 'react'
import ReactDOM from 'react-dom'
import '@atlaskit/css-reset'
import { DragDropContext } from 'react-beautiful-dnd'
import styled from 'styled-components'

import initialData from './initial-data'
import Column from './column'

const Container = styled.div`
  display:flex;
`
const shuffle =(arra1) => {
  var ctr = arra1.length, temp, index;

// While there are elements in the array
  while (ctr > 0) {
// Pick a random index
      index = Math.floor(Math.random() * ctr);
// Decrease ctr by 1
      ctr--;
// And swap the last element with it
      temp = arra1[ctr];
      arra1[ctr] = arra1[index];
      arra1[index] = temp;
  }
  return arra1;
}


class App extends React.Component {

  state = initialData;
  // constructor(){
  //   super();

  // }


  componentWillMount() {
    shuffle(this.state.columns.columnA.taskIds);
}
  onDragEnd = result => {

    const { destination, source, draggableId } = result

    if (!destination) {
      return
    }

    if (
      destination.droppableId === source.droppableId &&
      destination.index === source.index
    ) {
      return
    }
console.log("src",source);

    const start = this.state.columns[source.droppableId]
     console.log(start)
    const finish = this.state.columns[destination.droppableId]
    // console.log(finish)
    //   console.log(start===finish)
    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
      }


      console.log(this.state.columns.columnA.taskIds)
    console.log(  "after shift",this.state.columns.columnA.taskIds);

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

      this.setState(newState)

      return
    }

    const pattren = ['task-1', 'task-2', 'task-3', 'task-4','task-5','task-6','task-7','task-8','task-9','task-10','task-11','task-12','task-13'];
    // Moving from one list to another
    const startTaskIds = Array.from(start.taskIds)
    console.log(Array.from(start.taskIds))
    console.log("start",source.index)
    startTaskIds.splice(source.index, 1)
    // const pickeditem=startTaskIds[1];

    const newStart = {
      ...start,
      taskIds: startTaskIds
    }

console.log(startTaskIds)
    const finishTaskIds = Array.from(finish.taskIds)
    console.log(Array.from(finish.taskIds))
    finishTaskIds.splice(destination.index, 0, draggableId)
    const newFinish = {
      ...finish,
      taskIds: finishTaskIds
    }
console.log(finishTaskIds)
console.log("lastind",finishTaskIds[finishTaskIds.length-2])
console.log("dragable",draggableId)
// if(finishTaskIds[finishTaskIds.length-1<draggableId])
if(finishTaskIds.indexOf(draggableId)===pattren.indexOf(draggableId)){
console.log(finishTaskIds.length-1<draggableId)
console.log('check',(finishTaskIds.indexOf(draggableId)===pattren.indexOf(draggableId)));
    const newState = {
      ...this.state,
      columns: {
        ...this.state.columns,
        [newStart.id]: newStart,
        [newFinish.id]: newFinish
      }
    }


    this.setState(newState)
    console.log("nestates",newState);

     function sPlice(value,index2){

      value.splice(index2,1)
      }
    const index = this.state.columns.columnA.taskIds.indexOf(draggableId);



    sPlice(this.state.columns.columnA.taskIds,index)
    if(this.state.columns.columnA.taskIds.length==0){
      alert("you won the game ");
    }

   console.log("===============",this.state.columns.columnA.taskIds.indexOf(draggableId))        
  console.log() 
  // const itm = this.state.columns.columnA.taskIds.indexOf(draggableId);
  // console.log(itm)

//   const filter = this.state.columns.columnA.filter((column)=> col )
//   const index = this.state.columns.columnA.indexOf((column)=> this.state.columns.columnA.taskIds === this.state.columns.columnB.taskIds  )                     
//   this.state.columns.columnB.taskIds.splice(index,1)
}else{
    return;
}
  }


  render() {
    return (
      <DragDropContext onDragEnd={this.onDragEnd}>
        <Container>
          {this.state.columnOrder.map(columnId => {
            const column = this.state.columns[columnId]
            const tasks = column.taskIds.map(
              taskId => this.state.tasks[taskId]
            )

            return (
              <Column key={column.id} column={column} tasks={tasks} />
            )
          })}
        </Container>
      </DragDropContext>
    )
  }
}

const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)




    this one is column .js 

创建两列的组件,如果我们将其转换为类似this.props.column.id的道具,我将无法得到它。

    import React from 'react'
    import styled from 'styled-components'
    import Task from './task'
    import { Droppable } from 'react-beautiful-dnd'

    const Container = styled.div`
      margin: 8px;
      border: 1px solid lightgrey;
      border-radius: 2px;
      width: 220px;

      display: flex;
      flex-direction: column;
    `
    const Title = styled.h3`
      padding: 8px;
    `
    const TaskList = styled.div`
      padding: 8px;
      transition: background-color 0.2s ease;
      background-color: ${props =>
        props.isDraggingOver ? 'skyblue' : 'white'}
      flex-grow: 1;
      min-height: 100px;
    `



    export default class Column extends React.Component {



      render() {


        return (

          <Container>
            <Title>{this.props.column.title}</Title>
            <Droppable droppableId={this.props.column.id} type="TASK">
              {(provided, snapshot) => (
                <TaskList
                  ref={provided.innerRef}
                  {...provided.droppableProps}
                  isDraggingOver={snapshot.isDraggingOver}
                >
                  {shuffledArr.map((task, index) => (
                    <Task key={task.id} task={task} index={index} />
                  ))}
                  {provided.placeholder}
                </TaskList>
              )}
            </Droppable>
          </Container>
        )
      }

    }

    this is task.js component 

本节将如何转换为通用的组件以及this.props.task.id和其他道具应如何处理?如何在功能组件中使用它们

    import React from 'react'
    import styled from 'styled-components'
    import { Draggable } from 'react-beautiful-dnd'

    const Container = styled.div`
      border: 1px solid lightgrey;
      border-radius: 2px;
      padding: 8px;
      margin-bottom: 8px;
      transition: background-color 0.2s ease;
      background-color: ${props =>
        props.isDragDisabled
          ? 'lightgrey'
          : props.isDragging
            ? 'lightgreen'
            : 'white'};
    `

    export default class Task extends React.Component {
      render() {
        // const isDragDisabled = this.props.task.id === 'task-1'
        return (
          <Draggable
            draggableId={this.props.task.id}
            index={this.props.index}
           // isDragDisabled={isDragDisabled}
          >
            {(provided, snapshot) => (
              <Container
                {...provided.draggableProps}
                {...provided.dragHandleProps}
                ref={provided.innerRef}
                isDragging={snapshot.isDragging}
             //   isDragDisabled={isDragDisabled}
              >
                {this.props.task.content}

              </Container>
            )}
          </Draggable>
        )
      }
    }

0 个答案:

没有答案