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

react-chartjs-2自定义tooltip始终显示求助:opacity恒为1

Fixing Persistent Custom Tooltip in react-chartjs-2

Hey there, let's work through this tooltip issue together!

The core problem here is that when you disable the default tooltip with tooltips.enabled: false, Chart.js stops automatically updating the tooltipModel.opacity value. That’s why it stays stuck at 1, and your hide logic never runs. Instead of relying on opacity, we can use a far more reliable trigger: checking if the tooltipModel.dataPoints array has content.

Here’s how to adjust your code to fix this:

tooltips: {
  enabled: false,
  mode: 'x',
  intersect: false,
  custom: (tooltipModel) => {
    // Check if there are any data points to display in the tooltip
    if (!tooltipModel.dataPoints || tooltipModel.dataPoints.length === 0) {
      this.hide();
      return;
    }

    // Your existing logic for handling tooltip position and data display
    const date = tooltipModel.dataPoints[0].xLabel;
    const value = tooltipModel.dataPoints[0].yLabel;
    // this.setPositionAndData(top, left, date, value);
  },
}

Why this works:

When your mouse isn’t hovering over any data points that match your tooltip’s mode and intersect rules, Chart.js will pass an empty dataPoints array to the custom function. This empty array is a clear signal that the tooltip should be hidden—replacing the broken opacity check that wasn’t working for you.

If you ever need more precise control (like verifying the mouse is within the chart’s bounds), you could also use Chart.js’s getElementsAtEventForMode method. But checking dataPoints is the simplest, most direct fix for your current scenario.

内容的提问来源于stack exchange,提问作者Сергей Романовский

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:09:15