在我的项目中,我有两个节点(svg 框)和它们之间的连接(箭头)。
Node 是一个组件,它通过传递x
和y
坐标作为 props 来初始化:
let nodes = [];
nodes.push(<Node key={0} x={50} y={100} />);
nodes.push(<Node key={1} x={300} y={100} />);
现在我有一个Connection
组件,它应该有两个参数:一个Node
连接自和一个Node
连接到:
let connections = [];
connections.push(<Connection key={1} from={nodes[0]} to={nodes[1]} /> );
Node
被定义为@observer
并且有两个可观察的属性
@observer
export default class Node extends React.Component {
@observable left = 6;
@observable top = 8;
...
}
您可以拖放Node
,left
并且top
值将相应更改。
Connection
组件也被定义为@observer
并传入我们需要连接的节点的道具绑定到可观察变量:
@observer
export default class Connection extends React.Component {
@observable node_from;
@observable node_to;
componentDidMount() {
this.node_from = this.props.from;
this.node_to = this.props.to;
}
...
}
Nodes
然后Components
在 parent 的render()
方法中呈现,如下所示:
render() {
let nodes = [];
nodes.push(<Node key={0} x={50} y={100} />);
nodes.push(<Node key={1} x={300} y={100} />);
let connections = [];
connections.push(<Connection key={1} from={nodes[0]} to={nodes[1]} /> );
return (
<div>
<svg width={600} height={400}>
{connections}
{nodes}
</svg>
</div>
);
}
现在我的问题是我无法弄清楚如何修改我的Connection
组件,因此每当传递给它的节点之一“更改”(意味着它left
或被top
更改)时它都会收到通知,以便我可以在节点之间重新绘制一条线?
基本上我有两个问题:
- 能够从内部组件中获取
left
和top
变量(确定从 x;y 到什么 x;y 我应该画一条线的坐标);Node
Connection
Connection
仅在移动时重绘 a ,Node
仅连接正在移动的节点。