React 和 React-Draggable 中的 setState 问题

Issue with setState in React and React-Draggable

我在使用 React 中的 setState 函数时遇到问题。我正在使用 react-draggable 包,我可以拖动我的 div 但是当我释放鼠标按钮时它似乎没有设置 x y 坐标,所以 div 只是快速回到哪里它是。有人可以告诉我 onControlledDrag 在这里做错了什么吗?谢谢!

  export class DraggableAnswer extends React.Component {
  constructor(props, context) {
    super(props, context);

    this.controlledPosition ={ x: -25, y: 10};
  }
  onControlledDrag(e, position) {
    console.log(position);
    const {x, y} = position;
    this.setState({
      controlledPosition: {x: x, y: y}
    });
  }


  render() {
    const dragHandlers = {onStart: this.onStart, onStop: this.onStop};    

    return (
      <div className="draggableAnswerBlock">
            <Draggable
              zIndex={100}
              position={this.controlledPosition}
              {...dragHandlers}
              onDrag={this.onControlledDrag.bind(this)}>
                <div className="box">
                  Change my position
                </div>
            </Draggable>
      </div>
    )
  }
}

在构造函数中应该是:

constructor(props, context) {
  super(props, context);

  this.state = { controlledPosition: { x: -25, y: 10} };
}

然后在 return 中,您应该将 this.state.controlledPosition 传递给 Draggable。现在 this.controlledPosition 从不更新,所以它会在拖动完成后重置。