从子级调整父级大小

时间:2019-05-07 01:11:41

标签: javascript reactjs

我有一个SVG区域,其中包含一个矩形及其调整大小,调整大小是放置在矩形边界上的圆形,并且在移动调整大小时需要调整整个SVG的大小。

这是我节点的代码:

class Node extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: 0,
      tabIndex: 0,
      x: this.props.x,
      y: this.props.y,
    };
  }

  resizeNode = (clientX, clientY) => {
    let node = document.getElementById(this.state.id)
    console.log(node.getBoundingClientRect().left)
    const newWidth = this.state.width + 1;
    const newHeight = this.state.height + 1;
    this.setState({
      width: newWidth,
      height: newHeight,
    });
  }
  render() {
    const posVisibleRect = 6;
    return (
      <svg id={id} width={width} height={height} x={x} y={y} >
        <g>
          <rect x={posVisibleRect} y={posVisibleRect} width={width - (posVisibleRect * 2)} height={height - (posVisibleRect * 2)} />
        </g>
        {
          isResizerVisible &&
          <Resizer
            width={width}
            height={height}
            isResizable={isResizable}
            updateStateDraggable={this.updateStateDraggable.bind(this)}
            updateStateResizable={this.updateStateResizable.bind(this)}
            resizeNode={this.resizeNode.bind(this)}
          />
        }
      </svg>
    )
  }
}

这是调整大小代码:

class Resizer extends React.Component {
  componentDidMount(){
    window.addEventListener('mousemove', this.onMouseMove.bind(this), false);
    window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  }

  componentWillUnmount(){
    window.removeEventListener('mousemove', this.onMouseMove.bind(this), false);
    window.removeEventListener('mouseup', this.onMouseUp.bind(this), false);
  }

  onMouseDown(e) {
    e.preventDefault();
    this.props.updateStateResizable(true);
  }

  onMouseMove(e) {
    e.preventDefault();
    if( this.props.isResizable ){
      this.props.resizeNode(e.pageX, e.pageY);
    }
  }

  onMouseUp(e) {
    e.preventDefault();
    if( this.props.isResizable ){
      this.props.updateStateResizable(false);
    }
  }

  render() {
    return (
      <g
          onMouseDown={this.onMouseDown.bind(this)}
          onMouseUp={this.onMouseUp.bind(this)}
      >
        <circle
          style={style}
          cursor={BottomRight.cursor}
          cx={BottomRight.cx}
          cy={BottomRight.cy}
          r={style.r}
        />
      </g>
    );
  }
};

我有两个问题,因为我无法解决:

  1. 如何从子级(调整大小)调整父级(SVG)的大小?
  2. 您知道更好的选择吗?

0 个答案:

没有答案