项目实践7:antv/g6遇到的小问题

30 阅读1分钟
  • 出现改变字体类型和字体大小的时候文字消失的情况;为什么?刚刚发现问题了,我是用的一个全新的对象,只记录了变化的,但是这个graph只监听了第一层变化,深层的要把剩下的全部带上[流泪],也就是因为改变字体相关类型的时候会改动节点的style,这时候就要把原有节点style带上
  • render是异步

创建完graph之后不能立刻使用,因为他的对应方法可能还没拿到值,要判断graph的rendered是否准备好了再调用!

  • 拖拽实现:随机出现重复id

graph.ts:361 Uncaught Error: Node already exists: node-0.5811642289444856 at Graph.doAddNode (graph.ts:361:13) at graph.ts:380:14 at Graph.batch (graph.ts:97:5) at Graph.addNodes (graph.ts:378:10) at DataController.addNodeData (data.ts:341:16) at Graph.addNodeData (graph.ts:727:24) at Object.addNode (graphUtils.ts:248:11) at Object.addDragNode (store.ts:149:24) at onDrop (center-panel.tsx:30:42) 是因为把随机函数放到外面,但是内部重复调用的同一个已经产生的对象; // 节点默认配置模板

const defaultNode = {
  id: `node-${Math.random()}`,
  key: `node-${Math.random()}`,
  type: 'rect',
  style: {
    fill: '#fff',
    size: [60, 40],
    iconText: '新节点',
  },
};


// 边默认配置模板

const defaultEdge = {
  id: `edge-${Math.random()}`,
  key: `edge-${Math.random()}`,
  source: '',
  target: '',
  style: {
    stroke: '#000',
  },
};



/**
 * 创建一个通用的图形元素生成函数
 * @param {Object} defaultProps - 元素的默认属性
 * @returns {Function} 接收自定义属性并返回新元素的函数
 */
const createGraphElement = (defaultProps: any) => (customProps: any = {}) => {
  return produce(defaultProps, (draft: any) => {
    // 合并顶层属性
    Object.entries(customProps).forEach(([key, value]: [string, any]) => {
      if (key !== 'style') {
        draft[key] = value;
      }
    });

    // 合并样式属性(深层合并)
    if (customProps.style) {
      Object.entries(customProps.style).forEach(([key, value]: [string, any]) => {
        if (!draft.style) draft.style = {};
        (draft.style as any)[key] = value;
      });
    }
  });
};

// 创建节点的函数
export const createNode = createGraphElement(defaultNode);

// 创建边的函数
export const createEdge = createGraphElement(defaultEdge);

后面改成了直接把这个random放到函数里面,确保id唯一

  • 对象字面量里面,箭头函数不能集成this,到那时普通函数可以