ReactJS:组件之间的关系(依赖关系)

ReactJS: Relationship between Components (Dependency)

本文关键字:关系 依赖 组件 之间 ReactJS      更新时间:2023-09-26

我有两个组件:Table(父:Tables)和Connection(父:Connections)。TablesConnections的父级是App 。问题是在呈现连接之前需要渲染表。连接组件在两个表组件之间创建一个连接(带一条线),所以我要做的是读取Table组件的位置(使用 jQuery)并创建连接。但在呈现连接时,Table组件尚未呈现。

我能做些什么呢?有没有更好的方法?或者我可以定义依赖项吗?

更新:

实际上,它是两个Column组件之间的连接,但它们是可以通过拖放移动的Table组件的一部分。因此,该解决方案还应提供更新/刷新连接的可能性。

示例编码:

Table组件

class Table extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        x: 0,
        y: 0
    };
    this.dragMoveListener = this.dragMoveListener.bind(this);
    this.componentDidMount = this.componentDidMount.bind(this);
}
componentDidMount(){
  // ...
}
dragMoveListener(event) {
  // will be called after with drag'n'drop, so there is a refresh neccessary
  this.setState({x: this.state.x + event.dx, y: this.state.y + event.dy });
}
style() {
  return {
    transform: 'translate(' + this.state.x + 'px, ' + this.state.y + 'px)'
  };
}
render() {
  var self = this;
  var ncolumns = this.props.table.columns.map(function(c,i) {
    return <Column key={i} tablename={self.props.table.name} column={c} tindex={self.props.index} cindex={i}></Column>;
  });
  return (<div style={this.style()} className="table draggable">
            <div id={this.props.table.name} className="entry table-name">{this.props.table.name}</div>
            {ncolumns}
         </div>);
}
}

Connection组件:

class Connection extends React.Component {
    constructor(props) {
        super(props);
    }
    style(thickness,length,cx,cy,angle) {
        return {
            padding: '0px',
            margin: '0px',
            height: thickness + 'px',
            backgroundColor: '#eee',
            lineHeight: '1px',
            position: 'absolute',
            left: cx + 'px',
            top: cy + 'px',
            width: length + 'px',
            transform: 'rotate(' + angle + 'deg)'
        }
    }
    render() {
            var a = $('#'+this.props.connection.table_a + '-' + this.props.connection.column_a);
            var b = $('#'+this.props.connection.table_b + '-' + this.props.connection.column_b);
            // some math to get length, angle between tables/columns etc.
        return(<div style={this.style(thickness,length,cx,cy,angle)} />);
    }
}

在你的<App>创建一个回调函数tablesDidRender(),它将调用setState({tablesDidRender: true})App)。将该函数传递给<Tables>组件,并在componentDidMount(第一次呈现后调用的生命周期方法)中调用它。在您的<App>中,您现在可以基于this.state.tablesDidRender渲染<Connections>

  • 如果true:渲染<Connections>
  • 如果false:不渲染任何内容 ( null