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

如何在ReactJS中集成Heatmap.js热力图示例?

解决React中Heatmap.js的DOM操作问题(函数组件方案)

React中推荐通过useRef获取DOM元素替代原生querySelector,既符合React的DOM操作规范,又能为Heatmap.js提供容器。以下是简洁可复用的函数组件实现方案:

1. 安装Heatmap.js

通过npm安装依赖(若项目使用CDN,可跳过此步,直接在public/index.html中引入CDN脚本):

npm install heatmap.js

2. 实现可复用的热力图组件

import React, { useEffect, useRef } from 'react';
import h337 from 'heatmap.js';

const Heatmap = ({ data, maxValue, width = 400, height = 400 }) => {
  // 指向热力图容器的ref
  const containerRef = useRef(null);
  // 存储热力图实例,避免重复创建
  const heatmapInstance = useRef(null);

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

    // 初始化热力图实例
    if (!heatmapInstance.current) {
      heatmapInstance.current = h337.create({
        container: containerRef.current,
      });
    }

    // 更新热力图数据
    heatmapInstance.current.setData({
      data,
      max: maxValue,
    });

    // 组件卸载时清理实例,避免内存泄漏
    return () => {
      if (heatmapInstance.current) {
        heatmapInstance.current._renderer.canvas.remove();
        heatmapInstance.current = null;
      }
    };
  }, [data, maxValue]); // 数据或最大值变化时触发更新

  return (
    <div
      ref={containerRef}
      style={{
        width,
        height,
        position: 'relative',
        border: 'black solid 4px',
      }}
    />
  );
};

export default Heatmap;

3. 在项目中使用组件

import React from 'react';
import Heatmap from './Heatmap';

const App = () => {
  const heatmapPoints = [
    { x: 10, y: 10, value: 100 },
    { x: 100, y: 100, value: 50 },
    { x: 200, y: 200, value: 70 },
  ];

  return (
    <div>
      <h1>React Heatmap.js Demo</h1>
      <Heatmap data={heatmapPoints} maxValue={100} />
    </div>
  );
};

export default App;

核心说明

  • useRef的作用:containerRef安全获取DOM容器,heatmapInstance存储实例避免重复初始化;
  • 响应式更新:useEffect依赖data和maxValue,数据变化时自动更新热力图;
  • 可复用性:支持自定义宽高、数据和最大值,可直接在多个组件中复用;
  • 内存清理:组件卸载时销毁热力图实例并移除canvas,避免内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:42:47