询问有关在动态react 组件中添加和删除事件侦听器的建议.
所以,我有一个功能组件,它有一个对象列表.
它是这样呈现的:
objectList.map( (item) => {
return (
<div>
<some-component with props.id = item.id>
<some-bootstrap-icon>
<div>
)
}
我的目标是在用户单击图标并拖动鼠标时执行一些操作,并在鼠标打开后停止这些操作.在这些操作中,我需要了解鼠标移动了多少,列表中的哪个对象被"touch "了.
我现在有什么?
const some_action = (event, id) => {
... using event.movementX and id for some actions
}
const rendering_func = () => {
return ( {
objectList.map( (item) => {
const wrapper = (event) => {
some_action(event, item.id);
}
return <...>
<bootstrap-icon
onMouseDown={()=>
{window.addEventListener("mousemove", wrapper)}
}
onMouseUp={()=>
{window.removeEventListener("mousemove", wrapper)}
}
/>
<...>
} )
} )
}
事件监听器被成功添加,"some_action"函数完成了它的工作. 问题是:事件侦听器在鼠标朝上时未被删除.
Edit: Imagine the rotate icon in MS PowerPoint. When you click it, you can drag your mouse and the object will rotate. When you let go, the rotation stops. Basically I am trying to recreate the same functionality in terms of clicking, dragging and letting go of the icon.