Pee*_*eer 6 typescript reactjs react-dnd
我将react-dnd 与react maui 树一起使用。我的目标是一次拖动多个项目。
\n我的方法是将树中所有选定的节点存储在 useState 中作为 ids(strings) 数组。单击节点时,状态会更新,我可以成功选择多个节点。
\n问题始于阻力。该项目未更新。
\n// returns the state\n// initially e.g. ["4372"] later it should return the correct result\nconst getState = () => {\n return selectedTreeNodes\n } \nRun Code Online (Sandbox Code Playgroud)\nconst [, drag] = useDrag(() => ({\n type: "el",\n item: getState(),\n end: (item, monitor) => {\n const dropResult = monitor.getDropResult<DropResult>();\n if (item && dropResult) {\n alert(`You dropped ${item} ${selectedTreeNodes} into ${dropResult}!`);\n }\n console.log("DROPPED", item, "SELECTEDFIELDS", getState()); // all these are only logging the old state\n },\n collect: (monitor) => ({\n isDragging: monitor.isDragging(),\n handlerId: monitor.getHandlerId(),\n }),\n }));\nRun Code Online (Sandbox Code Playgroud)\n我尝试了不同的方法。selectedTreeNodes是 id 。它们从父组件传递下来,在那里它们是状态。当我单击父节点时,树将打开,并且该项目从第一个选定的父节点获取 id。
\n更改选择并开始拖动后,该项目不再更新,因此我不获取更新的 id,而只获取第一个。状态本身更新正确。
\n有什么建议么?
\n正如评论中所述,将useState 中的selectedTreeNode添加到useDrag的依赖项数组中将会发挥作用。
下面的代码(比问题中短一点)适合可能遇到同样问题的人:
const [, drag] = useDrag(
() => ({
type: "el",
item: selectedTreeNodes,
collect: (monitor) => ({
isDragging: monitor.isDragging(),
handlerId: monitor.getHandlerId(),
}),
}),
[selectedTreeNodes] // DEPENDENCY ARRAY HERE
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |