You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js页面渲染Mermaid图表失败,仅显示纯文本求解决方案

解决Next.js中Mermaid图表仅显示纯文本的问题

核心问题

你的代码存在三个关键问题导致Mermaid无法渲染:

  1. 未触发Mermaid解析逻辑:Mermaid不会自动扫描页面文本并渲染,必须主动调用其API完成解析渲染。
  2. JSX语法错误:JSX中需用className替代原生HTML的class;且调用displayChart时传入的entities未定义,应改为jsonentities。
  3. TypeScript类型错误:integer不是TypeScript的合法类型,需替换为number。

解决方案步骤

1. 安装Mermaid依赖

先在项目中安装Mermaid库:

npm install mermaid
# 或
yarn add mermaid
# 或
pnpm add mermaid

2. 修正并优化组件代码

使用useEffect在客户端组件挂载后调用Mermaid API渲染图表,同时修正所有语法/类型错误:

import { InferGetStaticPropsType, useEffect, useRef } from 'next';
import { GetStaticProps } from 'next';
import mermaid from 'mermaid';

interface Entity {
  entityid: number;
  entityname: string;
  entityparent: number | null;
  entitytype: string | null;
  system: number;
  systemname: string;
  entitylevel: string;
  haschildren: boolean;
}

export const getStaticProps: GetStaticProps = async (context) => {
  const res = await fetch('--host--');
  const jsonentities: Entity[] = await res.json();

  return {
    props: {
      jsonentities,
    },
  };
};

function displayChart(entities: Entity[]): string {
  // 示例Mermaid代码,后续可基于entities动态生成逻辑
  return `graph LR;
    A-->B;
    B-->C;
    B-->D;`;
}

function Display({ jsonentities }: InferGetStaticPropsType<typeof getStaticProps>) {
  const chartRef = useRef<HTMLDivElement>(null);
  const mermaidCode = displayChart(jsonentities);

  useEffect(() => {
    if (!chartRef.current) return;

    // 初始化Mermaid(可根据需求调整配置)
    mermaid.initialize({ startOnLoad: false });

    // 异步渲染图表
    const renderChart = async () => {
      try {
        const { svg } = await mermaid.render('mermaid-chart', mermaidCode);
        chartRef.current.innerHTML = svg;
      } catch (error) {
        console.error('Mermaid渲染失败:', error);
        chartRef.current.innerHTML = '图表渲染出错';
      }
    };

    renderChart();
  }, [mermaidCode]);

  return <div ref={chartRef} id="mermaid-chart"></div>;
}

export default Display;

关键说明

  • 客户端渲染适配:Mermaid依赖浏览器DOM环境,用useEffect确保渲染逻辑在组件挂载后执行,避免SSR期间出现环境不兼容错误。
  • 动态图表扩展:后续可修改displayChart函数,基于entities数组的实际数据动态生成Mermaid代码,实现业务所需的动态关系图。
  • 错误处理:添加渲染异常捕获,便于排查Mermaid语法错误或数据问题。

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:33:21