gojs在react中的使用:
由于官方文档给的实在是太难懂,所以自己写了一点文档
-
下载安装gojs
这个这里就不赘述了,网上还有各种资料有很多
-
例子:
此处是重点
import React, { Component } from "react"; import * as go from "gojs"; import { ReactDiagram } from "gojs-react"; class MainGraph extends Component { constructor(props) { super(props); this.state = { nodeArray: [], linkArray: [], }; } componentDidMount() { const nodeArray=[] const linkArray=[] ... ... ... //这里最好是从父组件传过来然后做更改 this.setState({ nodeArray, linkArray, }); } initDiagram = () => { const $ = go.GraphObject.make; const diagram = $(go.Diagram, { "undoManager.isEnabled": false, // enable undo & redo model: $(go.GraphLinksModel, { linkKeyProperty: "key", // IMPORTANT! must be defined for merges and data sync when using GraphLinksModel }), layout: $( go.TreeLayout, // specify a Diagram.layout that arranges trees { angle: 90, layerSpacing: 35 } ), }); ...//此处写正常节点的配置即可 go.AnimationManager.defineAnimationEffect( "fraction", function ( obj, startValue, endValue, easing, currentTime, duration, animation ) { obj.segmentFraction = easing( currentTime, startValue, endValue - startValue, duration ); } ); setTimeout(() => { diagram.nodes.each(function (node) { const status = node.elt(0).elt(0).Zj.nb.status; //主要想说明的就是这里动画配置由于initDiagram后react组件不会正确更新动画的效果(至少我在官方文档没找到)所以做了个定时器当然可能会有一些同步的bug,不过没有找到更好的替代方法 }); }, 1000); return diagram; }; render() { const { nodeArray, linkArray } = this.state; return ( {/**这里到目前为止还是没法做到图片的更新如果有异步操作则无法更新,建议的方法是在父组件加一个key并且值设定为传进来的节点或者连线数据**/} <div> <ReactDiagram initDiagram={this.initDiagram} nodeDataArray={nodeArray} linkDataArray={linkArray} /> </div> ); } } export default MainGraph;
官方实例最大的问题在于没有对怎么更新双向绑定的数据做说明,目前我的想法是通过key做强制更新,原因在于对于nodeArray如果放在子组件(父组件做ajax或者axios的操作则导致无法更新),所以目前想到改变key值得操作让其强制更新