我在使用setState函数时遇到了困难。我正在使用反应可拖动的包,我可以拖动我的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>
)
}
}
答案 0 :(得分:3)
在构造函数中应该是:
constructor(props, context) {
super(props, context);
this.state = { controlledPosition: { x: -25, y: 10} };
}
然后在返回时你应该将this.state.controlledPosition传递给Draggable。现在this.controlledPosition永远不会更新,所以当拖动完成时它会重置。