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

如何修改Recharts LineChart中鼠标悬停时的线条宽度

修改Recharts LineChart悬停时的线条宽度

要实现鼠标悬停激活实心点时增大线条宽度,有几种实用方法:

方法一:单线条状态控制

  1. 在组件内定义状态跟踪悬停状态:
import { useState } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid } from 'recharts';

const MyChart = () => {
  const [isLineHovered, setIsLineHovered] = useState(false);
  
  return (
    <LineChart width={600} height={300} data={yourData}>
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="name" />
      <YAxis />
      <Line
        dataKey="value"
        stroke="#8884d8"
        // 悬停时线条宽度设为4,默认2,可自行调整数值
        strokeWidth={isLineHovered ? 4 : 2}
        // 自定义激活点样式,和线条宽度匹配
        activeDot={{ r: 6, fill: '#8884d8' }}
        // 绑定鼠标事件更新状态
        onMouseEnter={() => setIsLineHovered(true)}
        onMouseLeave={() => setIsLineHovered(false)}
      />
    </LineChart>
  );
};

方法二:多线条状态控制

如果图表包含多条线,需要跟踪当前悬停的线条标识:

const MyChart = () => {
  const [hoveredDataKey, setHoveredDataKey] = useState(null);
  
  return (
    <LineChart width={600} height={300} data={yourData}>
      {/* 基础组件省略 */}
      <Line
        dataKey="sales"
        stroke="#8884d8"
        strokeWidth={hoveredDataKey === 'sales' ? 4 : 2}
        activeDot={{ r: 6 }}
        onMouseEnter={() => setHoveredDataKey('sales')}
        onMouseLeave={() => setHoveredDataKey(null)}
      />
      <Line
        dataKey="profit"
        stroke="#82ca9d"
        strokeWidth={hoveredDataKey === 'profit' ? 4 : 2}
        activeDot={{ r: 6 }}
        onMouseEnter={() => setHoveredDataKey('profit')}
        onMouseLeave={() => setHoveredDataKey(null)}
      />
    </LineChart>
  );
};

方法三:CSS样式控制

通过CSS类名直接控制悬停样式,适合全局统一调整:

  1. 给Line组件添加className:
<Line
  dataKey="value"
  stroke="#8884d8"
  className="recharts-custom-line"
  activeDot={{ r: 6 }}
/>
  1. 在CSS文件中添加样式:
.recharts-custom-line:hover {
  stroke-width: 4 !important;
}

注:因为Recharts会给线条添加内联样式,所以需要用!important确保样式优先级足够。

注意事项

  • 调整strokeWidth的数值可自定义线条粗细,按需修改;
  • activeDot的r(半径)属性可配合线条宽度调整,保持视觉协调;
  • 如果使用Tooltip组件,确保鼠标事件逻辑和Tooltip触发不冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 17:11:13