2016-06-12 169 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