2016-09-23 113 views
0

DragAndResizeBox.js父組件可以顯示子組件狀態嗎?

我用ref={(c) => { this.resizableandmovable = c; }}ResizableAndMovablereact-rnd文件稱
我發現我能得到this.resizableandmovable.state.xthis.resizableandmovable.state.y

class DragAndResizeBox extends Component { 

    constructor(props) { 
    super(props); 
    } 

    onDragStop = (event, ui) => { 
    console.log("[onDragStop]state:",this.resizableandmovable.state) 
    } 

    render() { 
    const { canDrop, isOver, connectDropTarget } = this.props; 
    const isActive = canDrop && isOver; 
    const { contentObjectId, boxType } = this.props 

    return connectDropTarget(
     <div> 
     <ResizableAndMovable 
      ref={(c) => { this.resizableandmovable = c; }} 
      initial = {{ 
      x:this.props.axisX ? this.props.axisX: 0, 
      y:this.props.axisY ? this.props.axisY :0, 
      width:this.props.width ? this.props.width: 200, 
      height:this.props.height ? this.props.height: 200, 
      }} 
      onDragStop={this.onDragStop} 
     > 
      <div className={this.getCssStyle(boxType)}> 
      {this.show(contentObjectId)} 

      </div> 
     </ResizableAndMovable> 
     </div> 
    ); 
    } 
} 

enter image description here

但我想說明的位置x,y 我怎樣才能得到脂肪this.resizableandmovable.state她的組件?

**父親組件**

import DragAndResizeBox from './DragAndResizeBox'; 
boxes.map(box => { 
    return (
     <DragAndResizeBox key={box.id} /> 
); 
}); 

// Can I directly access this.resizableandmovable.state ??? 
//<div>X:<textarea>{this.resizableandmovable.state.x}</textarea>Y:{this.resizableandmovable.state.y}<textarea></textarea> 

回答

1

簡短的回答是不,你不能。

你可以而且應該做的是將狀態存儲在父組件中。並通過道具傳遞給子組件。 更新函數通常也坐在父組件內並作爲道具傳遞給孩子。