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

如何在Recharts中实现柱状图Hover时填充颜色切换?

Recharts柱状图实现动态颜色与Hover切换效果

我有一个基于Recharts的柱状图,柱子颜色根据y轴数值(uv字段)填充:当uv>3000时为绿色(#00ff00),其余为红色(#ff0000)。希望实现鼠标Hover时,红色柱子切换为紫色,绿色柱子切换为蓝色,该如何实现?


实现方案

核心思路

通过给数据预定义初始颜色和Hover颜色,结合组件状态跟踪Hover的柱子索引,动态设置Bar组件的fill属性来实现效果。

具体步骤

  • 给每条数据添加fill(初始颜色)和hoverFill(Hover时颜色)字段,按业务规则赋值
  • 使用React状态记录当前Hover的柱子索引
  • 给Bar组件绑定鼠标进入/离开事件,更新Hover状态
  • 在fill属性中通过条件判断,动态切换颜色

修改后的完整代码

import { useState } from 'react';
import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { CustomizedLabel } from './CustomizedLabel'; // 保留原有自定义标签组件

// 示例数据(可替换为你的实际数据)
const data = [
  { name: 'Page A', uv: 4000 },
  { name: 'Page B', uv: 3000 },
  { name: 'Page C', uv: 2000 },
  { name: 'Page D', uv: 2780 },
  { name: 'Page E', uv: 1890 },
  { name: 'Page F', uv: 2390 },
  { name: 'Page G', uv: 3490 },
];

export default function App() {
  // 维护当前hover的柱子索引状态
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);

  // 预处理数据,添加初始颜色和hover颜色
  const processedData = data.map(item => {
    if (item.uv > 3000) {
      return {
        ...item,
        fill: '#00ff00',
        hoverFill: '#0000ff'
      };
    } else {
      return {
        ...item,
        fill: '#ff0000',
        hoverFill: '#800080'
      };
    }
  });

  return (
    <div style={{ height: 300 }}>
      <ResponsiveContainer width="100%" height="100%">
        <BarChart
          width="100%"
          height={300}
          data={processedData}
          margin={{ top: 50, right: 30, left: 20, bottom: 5 }}
        >
          <XAxis
            dataKey="name"
            tickLine={false}
            style={{ fontSize: 14, color: '#000000', fontFamily: 'Arial', fontWeight: 'bold' }}
          />
          <YAxis tickLine={false} />
          <Tooltip />
          <Legend />
          <Bar
            dataKey="uv"
            label={<CustomizedLabel />}
            // 动态设置填充颜色
            fill={(entry) => hoverIndex === entry.index ? entry.hoverFill : entry.fill}
            // 鼠标进入时记录索引
            onMouseEnter={(_, index) => setHoverIndex(index)}
            // 鼠标离开时清空索引
            onMouseLeave={() => setHoverIndex(null)}
          />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

关键细节说明

  • 预处理数据时,直接给每条数据绑定对应的初始颜色和Hover颜色,避免重复判断
  • 通过hoverIndex状态精准定位当前Hover的柱子,确保只有目标柱子切换颜色
  • fill属性支持接收函数,动态返回对应颜色,无需额外DOM操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 10:43:16