TypeScript项目使用GoJS ReactDiagram组件报错的解决咨询
解决GoJS ReactDiagram在TypeScript里的"JSX element class does not support attributes"报错
报错原因
这个问题本质是TypeScript无法识别ReactDiagram组件的props属性——要么是没装对应的类型定义包,要么是导入方式不对,导致TS没法解析组件的属性类型。
一步步解决
1. 安装必要的类型依赖
GoJS和gojs-react的官方类型包必须装上,不然TS根本不知道组件的props结构:
npm install @types/gojs @types/gojs-react --save-dev
2. 修正导入方式或补充类型声明
如果装了类型包还是报错,试试调整导入方式:
// 换成默认导入尝试 import ReactDiagram from 'gojs-react';
要是问题依旧,可以在文件顶部加个临时类型声明(临时救急,优先使用官方类型):
declare module 'gojs-react' { import * as go from 'gojs'; import React from 'react'; interface ReactDiagramProps { initDiagram: () => go.Diagram; divClassName?: string; nodeDataArray?: any[]; linkDataArray?: any[]; } export const ReactDiagram: React.ComponentType<ReactDiagramProps>; }
3. 检查TypeScript配置
确保tsconfig.json里的jsx选项设置正确,React 17+推荐使用react-jsx:
{ "compilerOptions": { "jsx": "react-jsx", "esModuleInterop": true, "allowSyntheticDefaultImports": true } }
4. 代码优化(非报错相关,但建议修改)
你当前把ipcRenderer.on直接写在组件函数内部,会导致每次组件渲染都重复绑定监听,容易引发问题,建议移到useEffect中:
useEffect(() => { ipcRenderer.send("getGoals"); const handleGoals = (e: any, goals: GoalModel[]) => { console.log(goals); setGoalsList(goals); }; ipcRenderer.on("goals", handleGoals); // 组件卸载时移除监听,避免内存泄漏 return () => { ipcRenderer.removeListener("goals", handleGoals); }; }, []);
调整树形布局到类似Minecraft成就的样式
如果要实现Minecraft那种纵向的成就树结构,修改TreeLayout的参数即可:
diagram.layout = $(go.TreeLayout, { layerSpacing: 40, // 层级之间的垂直间距 nodeSpacing: 20, // 同层级节点的水平间距 angle: 90, // 设置为90度实现从上到下的纵向树形 alignment: go.TreeLayout.AlignmentStart // 节点左对齐 });
内容的提问来源于stack exchange,提问作者Dolfina
相关产品推荐
相关产品推荐

