spec.type 必须在react-dnd中定义

Hor*_*ora 8 javascript reactjs react-dnd

我正在尝试使用 React React-dnd 制作 Trello 克隆。 只需输入下面的代码我就会收到错误

 const [{ isDragging }, dragRef] = useDrag({
    item: { type: "CARD" },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

必须定义spec.type

invariant
C:/Users/lucca/Documents/GitHub/2B-task/src/index.ts:28
 25  |   );
  26 | } else {
  27 |   let argIndex = 0;
> 28 |   error = new Error(
     | ^  29 |     format.replace(/%s/g, function() {
  30 |       return args[argIndex++];
  31 |     })
Run Code Online (Sandbox Code Playgroud)

Gav*_*son 13

使固定:

在 React DnD 的 ^14 版本中,API 格式发生了变化。该类型现在与项目解耦:

// Pre-v14
useDrag({
   // item defined here to get a type
   item: { type: BOX } },
   // ...but the actual item is created here
   begin: () => ({ id })
})

// v14
useDrag({
   // type is now listed by itself, not inside of item
   type: BOX,
   item: () => ({id})
})
Run Code Online (Sandbox Code Playgroud)

总而言之:

有关此的文档: https://github.com/react-dnd/react-dnd/releases/tag/v14.0.0

这应该适用于所有最新的 React 版本。我的版本是:

"react": "^17.0.2",
"react-dnd": "^15.0.2",
"react-dnd-html5-backend": "^15.0.2",
Run Code Online (Sandbox Code Playgroud)


ava*_*tar 6

这里type应该作为 useDrag 的 prop 传递。请确保您也在 中CARD传递相同的类型。您可以在这里找到更多参考资料。useDropaccept

const [{ isDragging }, dragRef] = useDrag({
    type: "CARD",
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

 const [collectedProps, drop] = useDrop({
    accept: "CARD",
    collect: (monitor: any) => { ... },
    ...
});

Run Code Online (Sandbox Code Playgroud)