react-chartjs-2自定义tooltip始终显示求助:opacity恒为1
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,提问作者Сергей Романовский

