0
import { useEffect } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import { useAppState } from '../AppStateContext';
import { DragItem } from '../DragItem';
export const useItemDrag = (item: DragItem) => {
  const { dispatch } = useAppState();
  const [, drag, preview] = useDrag({
    item,
    begin: () => dispatch({ type: 'SET_DRAGGED_ITEM', payload: item }),
    end: () => dispatch({ type: 'SET_DRAGGED_ITEM', payload: undefined }),
        
  });
  useEffect(() => {
    preview(getEmptyImage(), { captureDraggingState: true });
  }, [preview]);
  return { drag };
};

react-dnd 在此处发出 带有错误消息的图像

在 useDrag 上收到此错误

Argument of type '{ item: DragItem; begin: () => any; end: () => any; }' is not assignable to parameter of type 'FactoryOrInstance<DragSourceHookSpec<unknown, unknown, any>>'.

对象字面量只能指定已知属性,并且类型 'FactoryOrInstance<DragSourceHookSpec<unknown, unknown, any>>' 中不存在 'begin'

4

2 回答 2

0

上面的答案对我不起作用,我所做的是以下,我返回了 Item + dispatch 回调。但无论如何,谢谢你,你的回答为我指明了正确的方向。

import React from "react";

import { useDrag } from "react-dnd";
import { useAppState } from "./AppContext";
import { DragItem } from "./DragItem";



export const useItemDrag = (item: DragItem) => {
  const { dispatch } = useAppState();

  const [{ isDragging }, drag] = useDrag({
    type: item.type, //Contains data about the item we're trying to drag
   //Item replaced Begin in the new version of React DnD
    item: () => {
        return [item, 
            dispatch({
                type: "SET_DRAGGED_ITEM",
                payload: item
                }) //Need to return Item + action
        ]
    },

    end : () => 
        
        dispatch({
        type: "SET_DRAGGED_ITEM",
        payload: undefined
        })
    ,
        
    collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      })
    })
    
    return {drag}
}
于 2021-11-13T20:28:35.627 回答
0

开始规范在 react-dnd v14 中被贬值,使用 item 代替并且在 useDrag 中需要类型规范。链接在这里

import { useEffect } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import { useAppState } from '../AppStateContext';
import { DragItem } from '../DragItem';
export const useItemDrag = (item: DragItem) => {
  const { dispatch } = useAppState();
  const [, drag, preview] = useDrag({
    type: item.type,
    item: () => dispatch({ type: 'SET_DRAGGED_ITEM', payload: item }),
    end: () => dispatch({ type: 'SET_DRAGGED_ITEM', payload: undefined }),
    
  });
  useEffect(() => {
    preview(getEmptyImage(), { captureDraggingState: true });
  }, [preview]);
  return { drag };
};
于 2021-08-29T03:30:03.803 回答