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

React中使用Chart.js实现鼠标悬停显示垂直线求助

实现鼠标悬停时显示垂直线的修正方案

你的代码思路是对的,问题出在插件的配置位置和Chart.js的细节处理上,下面是修正后的完整代码及关键说明:

import React, { Component } from "react";
import "../App.css";
import { Line } from "react-chartjs-2";
import { Chart as ChartJS, Filler } from "chart.js/auto";

export default class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mapRecv: props.data[0],
      type: props.data[1],
    };
  }

  render() {
    return (
      <>
        <Line
          className="chart"
          data={{
            labels: this.state.mapRecv["stockChartXValues"],
            datasets: [
              {
                label: `${this.state.type} Price USD`,
                data: this.state.mapRecv["stockChartYValues"],
                fill: true,
                backgroundColor: ["rgba(75, 192, 192, 0.2)"],
                borderColor: "rgba(75, 192, 192, 1)",
                borderWidth: 2,
              },
            ],
          }}
          options={{
            scales: {
              x: {
                grid: {
                  drawOnChartArea: false,
                },
              },
              y: {
                id: 'y'
              }
            },
            elements: {
              point: {
                radius: 0,
              },
            },
            plugins: {
              legend: {
                display: false,
              },
              tooltip: {
                mode: 'index',
                intersect: false
              },
              afterDraw: (chart) => {
                const activeElements = chart.tooltip?._active;
                if (!activeElements || activeElements.length === 0) return;

                const activeElement = activeElements[0];
                const x = activeElement.element.x;
                const yAxis = chart.scales['y'];
                const ctx = chart.ctx;

                ctx.save();
                ctx.beginPath();
                ctx.setLineDash([5, 5]);
                ctx.moveTo(x, yAxis.top);
                ctx.lineTo(x, yAxis.bottom);
                ctx.lineWidth = 1;
                ctx.strokeStyle = "rgba(0, 0, 255, 0.4)";
                ctx.stroke();
                ctx.restore();
              }
            },
            interaction: {
              intersect: false,
              mode: "index",
            },
            spanGaps: true,
          }}
        />
      </>
    );
  }
}

关键修正点:

  • 插件位置调整:将afterDraw钩子从组件的plugins属性移到options.plugins下,这是react-chartjs-2配置实例级插件的正确方式,之前的写法会导致插件无法绑定到当前图表实例。
  • 轴的精准获取:使用chart.scales['y']通过轴ID获取y轴对象,避免因Chart.js版本差异导致的属性访问异常。
  • 代码健壮性优化:增加了activeElements的空值判断,防止鼠标离开图表时出现报错。

修改后,鼠标悬停在图表区域(无需精准点到数据点)时,会自动显示一条贯穿y轴的虚线垂直线,和你想要的效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:21:22