gpt4 book ai didi

javascript - 为什么我的事件监听器回调没有使用正确的状态?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:29 27 4
gpt4 key购买 nike

我有一个组件可以使包裹的元素可拖动。当我开始拖动时,我将事件监听器添加到窗口以进行拖放。

    function start_drag({ x, y }) {
window.addEventListener('mouseup', trigger_drop);
window.addEventListener('mousemove', drag_move);
dispatch({ type: DispatchActions.START, x: x, y: y });
}

通过这些回调:

    const trigger_drop = (e) => {
//if (!dragging) { return; }
end_drag();
if (deliver()) {
if (props.onDrop) {
props.onDrop(e);
}
}
}

const drag_move = (e) => {
//if (!state.dragging) { return; }
dispatch({ type: DispatchActions.MOVE, x: e.x, y: e.y });
if (props.onDragMove) {
props.onDragMove(e);
}
}

但是,这些回调使用它们自己的状态和调度版本。在尝试了一些方法后,我无法解决这个问题,此外,我对“this”在这里的运作方式感到困惑。

我在 React 工作,只使用带有 React Hooks 的功能组件来处理状态等。许多其他 stackoverflow 问题的答案是使用绑定(bind)/箭头函数。如您所见,我将我的回调声明为箭头函数(不起作用),但这让我遇到了一些奇怪的事情;当我尝试绑定(bind)时,我发现我的功能组件中有 this === undefined。这大概是有关系的。我对此的搜索只得出答案说要在 React.Component 类的构造函数中绑定(bind)它,这在这里不起作用。

这里是模块的完整代码:

import React, { useContext, useEffect, useReducer } from 'react';
import { DragContext } from 'client/contexts/DragContext';
import dragtarget from './DragTarget.module.css';


const DispatchActions = {
MOVE: 'move',
START: 'start',
STOP: 'stop'
}

function reducer(state, action) {
switch(action.type) {
case DispatchActions.MOVE:
return { ...state, offset_x: action.x - (state.start_x + state.offset_x), offset_y: action.y - (state.start_y + state.offset_y) };
case DispatchActions.START:
return { ...state, dragging: true, start_x: action.x, start_y: action.y, offset_x: 0, offset_y: 0 };
case DispatchActions.STOP:
return { ...state, dragging: false };
default:
return state;
}
}


export default function DragTarget(props) {
const { drag, deliver } = useContext(DragContext);
const [state, dispatch] = useReducer(reducer, {
dragging: false,
start_x: 0, start_y: 0,
offset_x: 0, offset_y: 0
});

useEffect(() => {
return () => {
end_drag();
};
}, []);


function start_drag({ x, y }) {
window.addEventListener('mouseup', trigger_drop);
window.addEventListener('mousemove', drag_move);
dispatch({ type: DispatchActions.START, x: x, y: y });
}

function end_drag() {
window.removeEventListener('mouseup', trigger_drop);
window.removeEventListener('mousemove', drag_move);
dispatch({ type: DispatchActions.STOP });
}

const trigger_drag = (e) => {
e.stopPropagation();
e.preventDefault();
if (drag(props.payload)) {
start_drag({ x: e.x, y: e.y });
if (props.onDragStart) {
props.onDragStart();
}
}
}

const drag_move = (e) => {
//if (!state.dragging) { return; }
dispatch({ type: DispatchActions.MOVE, x: e.x, y: e.y });
if (props.onDragMove) {
props.onDragMove(e);
}
}

const trigger_drop = (e) => {
//if (!state.dragging) { return; }
end_drag();
if (deliver()) {
if (props.onDrop) {
props.onDrop(e);
}
}
}


return (
<div className={`${props.className} ${state.dragging ? dragtarget.dragging : null}`} style={{ transform: `translate(${state.offset_x}px, ${state.offset_y}px)` }} onMouseDown={trigger_drag}>
{props.children}
</div>
);
}

预期:在 window.mouseup 上,我希望回调 trigger_drop 访问正确的 state.draggingdispatch。与 window.mousemove 上的 drag_move 相同。

当前:在 window.mouseup 上,回调 trigger_drop 的 state.dragging 副本返回 false(而不是引用正确的 true),并且 drag_move 正在调度到其中包含未定义元素的状态(state === {dragging: true, start_x: undefined, start_y: undefined, offset_x: NaN, offset_y: NaN})。

我希望我解释清楚了,如果没有请告诉我。提前感谢您的帮助!

最佳答案

一种更简单的方法是放弃分派(dispatch)异步操作,而是利用可重用组件将其自身状态作为具有同步 setState 回调更新的单个对象来处理。

例如,您可以使用两个事件监听器和一个事件回调来简化您的逻辑:一个事件监听器用于 mouseup(鼠标单击)以保持元素,另一个事件监听器用于 mousemove (按住鼠标单击并移动鼠标时)平移元素,最后您可以使用元素的 onMouseDown(鼠标单击释放)事件回调在其当前位置释放自身。

工作示例(此示例使用 styled-components 以获得更清晰的代码,但您不需要这样做):

Edit Drag and Drop Content Example


组件/DragContainer/index.js

import styled from "styled-components";

export default styled.div.attrs(({ height, width, x, y }) => ({
style: {
transform: `translate(${x - width / 2}px, ${y - height / 2}px)`
}
}))`
cursor: grab;
position: absolute;
padding: 10px;
border-radius: 4px;

background-color: red;

${({ isDragging }) =>
isDragging &&
`
opacity: 0.5;
cursor: grabbing;
z-index: 999999;
`}
`;

components/Draggable/index.js

import React, {
useState,
useRef,
useEffect,
useCallback,
useLayoutEffect
} from "react";
import PropTypes from "prop-types";
import DragContainer from "../DragContainer";

const Draggable = ({ children, position }) => {
const dragRef = useRef(null);

const [state, setState] = useState({
isDragging: false,
translateX: position.x,
translateY: position.y,
height: 0,
width: 0
});

// mouse move
const handleMouseMove = useCallback(
({ clientX, clientY }) => {
if (state.isDragging) {
setState(prevState => ({
...prevState,
translateX: clientX,
translateY: clientY
}));
}
},
[state.isDragging]
);

// mouse left click release
const handleMouseUp = useCallback(() => {
if (state.isDragging) {
setState(prevState => ({
...prevState,
isDragging: false
}));
}
}, [state.isDragging]);

// mouse left click hold
const handleMouseDown = useCallback(() => {
setState(prevState => ({
...prevState,
isDragging: true
}));
}, []);

// before painting, get element height and width
// and zero out its position (this is
// necessary to force the cursor to point at the
// center of the element when dragging it)
useLayoutEffect(() => {
if (state.height < 1 && state.width < 1) {
const { offsetHeight, offsetWidth } = dragRef.current;
setState(prevState => ({
...prevState,
translateX: position.x + offsetWidth / 2,
translateY: position.y + offsetHeight / 2,
height: offsetHeight,
width: offsetWidth
}));
}
}, [position, state, setState, dragRef]);

useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp);

return () => {
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
}, [handleMouseMove, handleMouseUp]);

return (
<DragContainer
ref={dragRef}
isDragging={state.isDragging}
onMouseDown={handleMouseDown}
x={state.translateX}
y={state.translateY}
height={state.height}
width={state.width}
>
{children}
</DragContainer>
);
};

Draggable.propTypes = {
children: PropTypes.node.isRequired,
position: PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number
})
};

Draggable.defaultProps = {
position: {
x: 10,
y: 10
}
};

export default Draggable;

index.js

import React, { Fragment } from "react";
import { render } from "react-dom";
import { Draggable, Title } from "./components";

const App = () => (
<Fragment>
<Draggable position={{ x: 20, y: 20 }}>
<Title>Hello</Title>
</Draggable>
<Draggable position={{ x: 140, y: 20 }}>
<Title>Goodbye</Title>
</Draggable>
</Fragment>
);

render(<App />, document.getElementById("root"));

关于javascript - 为什么我的事件监听器回调没有使用正确的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57422136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com