十四、react-hooks和react-dnd

hooks

  • 注意:hooks需要React v16.7.0-alpha以上才支持
  • 只能放到function里面
    使用react-dnd注意到package.json有两句
    "peerDependencies": {
        "react": ">= 16.8",
        "react-dom": ">= 16.8"
    }

官方例子

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    

You clicked {count} times

); }

react-dnd

import React, {useCallback, useState} from 'react'
import {DndProvider} from 'react-dnd'
import HTML5Backend from 'react-dnd-html5-backend'
import Container from './Container'

const ImageView = ({src}) => {
  const [hideSourceOnDrag, setHideSourceOnDrag] = useState(true)
  const toggle = useCallback(() => setHideSourceOnDrag(!hideSourceOnDrag), [
    hideSourceOnDrag,
  ])
  return (
    

{src}
) } export default ImageView;
import React, { useState } from 'react'
import {useDrag, useDrop} from 'react-dnd'
import update from 'immutability-helper'

const styles = {
  width: '95%',
  height: '90vh',
  position: 'relative',
}

const style = {
  position: 'absolute',
  width: '100%',
  backgroundColor: 'white',
  cursor: 'move',
}

const Box = ({ id, left, top, hideSourceOnDrag, children }) => {
  const [{ isDragging }, drag] = useDrag({
    item: { id, left, top, type: 'box' },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  })
  if (isDragging && hideSourceOnDrag) {
    return 
} return (
{children}
) } const Container = ({ hideSourceOnDrag, src }) => { const [boxes, setBoxes] = useState({ a: { top: 20, left: 80, title: 'Drag me around' }, }) const [, drop] = useDrop({ accept: 'box', drop(item, monitor) { const delta = monitor.getDifferenceFromInitialOffset() const left = Math.round(item.left + delta.x) const top = Math.round(item.top + delta.y) moveBox(item.id, left, top) return undefined }, }) const moveBox = (id, left, top) => { setBoxes( update(boxes, { [id]: { $merge: { left, top }, }, }), ) } return (
{Object.keys(boxes).map(key => { const { left, top, title } = boxes[key] return ( {title} 图片 ) })}
) } export default Container

你可能感兴趣的:(十四、react-hooks和react-dnd)