2016-06-12 167 views
1

我在使用setState函数时遇到了困难。我正在使用react-draggable软件包,我可以拖动我的div,但是当我释放鼠标按钮时,它似乎没有设置xy坐标,因此div只是回到原来的位置。有人可以告诉我我在做什么错了onControlledDrag吗?谢谢!React和React-Draggable中的setState问题

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> 
    ) 
    } 
} 

回答

3

在构造函数应该是:

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

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

,然后在返回你应该通过this.state.controlledPosition到拖动。现在,this.controlledPosition永远不会更新,因此当拖动完成时它会重置。

+0

非常感谢你,这真的为我阐明了整个this.state和setState关系是如何工作的! – Coherent