可以使父组件显示子组件状态吗?

时间:2016-09-23 05:30:19

标签: reactjs redux

DragAndResizeBox.js

我在ref={(c) => { this.resizableandmovable = c; }}中使用ResizableAndMovable作为react-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 个答案:

答案 0 :(得分:1)

简短的回答是不可以的。

您可以而且应该做的是将状态存储在父组件中。并通过道具传递给子组件。 更新函数通常也位于父组件内部,并作为道具传递给子组件。

相关问题