【发布时间】:2020-04-02 13:46:03
【问题描述】:
const ControlPanel = ({ mainSectionRef }) => {
const [canMove, setCanMove] = useState(false)
const classes = useStyles();
const toolbarRef = useRef();
const onMouseMove = function (e) {
const { x, y } = getMouseCoordinatesOnCanvas(e, mainSectionRef.current);
toolbarRef.current.style.left = x +'px';
toolbarRef.current.style.top = y + 'px';
}
const setCan = () => {
setCanMove(!canMove)
}
if (mainSectionRef.current) {
//issue is here!!!!
mainSectionRef.current.removeEventListener('mousemove', onMouseMove, true)
if (canMove) {
mainSectionRef.current.addEventListener('mousemove', onMouseMove, true)
}
}
return (
<Toolbar ref={toolbarRef}>
<RadioButtonUncheckedIcon />
<CropSquareIcon />
<ArrowRightAltIcon />
<CloseIcon />
<DragIndicatorIcon style={{ backgroundColor: canMove ? "red" : "inherit" }} onClick={setCan}/>
</Toolbar >
);
}
export default ControlPanel;
每当组件中发生状态更改时,我都会尝试删除事件侦听器。 mainSectionref 是父 div,控制面板是子组件。我正在尝试在按钮的mainSectiononClick 中移动控制面板。该事件确实被添加但在状态更改时,它似乎并没有删除事件侦听器。我能知道出了什么问题吗?
【问题讨论】:
标签: javascript reactjs dom-events