Mis*_*rLA 6 javascript reactjs react-dnd
当我以自己的方式拖动项目时,我试图定义项目类型。但是,如果我这样做并拖动项目,就会出现问题,它会在删除项目后向我显示“不变违规:必须定义项目类型”。这意味着我有一个包含 ItemTypes 的文件,其中定义了所有内容:
export const ItemTypes = {
'CARD': "card",
'PHONE': "phone",
'WEAPON': "weapon",
'FOOD': "food",
'DRINK': "drink"
};
Run Code Online (Sandbox Code Playgroud)
在主库存上,项目数组就像这样
const [items, setItems] = useState([
{
type: "PHONE",
label: "test",
itemname: "test",
pieces: 10,
itemweight: 0.2
},
{
type: "CARD",
label: "test5",
itemname: "test5",
pieces: 5,
itemweight: 0.2
}
]);
Run Code Online (Sandbox Code Playgroud)
以及项目组件,我在其中定义被拖动的项目:
const Item = props => {
const [{ isDragging }, drag] = useDrag({
item: {
type: ItemTypes[props.type],
index: props.index,
label: props.label,
itemname: props.name,
pieces: props.pieces,
weight: props.itemweight
},
collect: (monitor) => ({
isDragging: !!monitor.isDragging()
})
});
Run Code Online (Sandbox Code Playgroud)
所以最后这意味着当我将项目放在目标容器上时,我收到错误“不变违规:必须定义项目类型”。
由于 DnD v14 API 的更改,您需要将“type”键从“item”键中移出:
const Item = props => {
const [{ isDragging }, drag] = useDrag({
item: {
index: props.index,
label: props.label,
itemname: props.name,
pieces: props.pieces,
weight: props.itemweight
},
type: ItemTypes[props.type], //MOVE THIS OUTSIDE ITEM OBJECT
collect: (monitor) => ({
isDragging: !!monitor.isDragging()
})
});
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)
| 归档时间: |
|
| 查看次数: |
10050 次 |
| 最近记录: |