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

如何基于Rechart的activeDot动态修改目标显示数值?

实现Rechart悬停数据点时显示对应Y值

实现思路

通过React状态管理存储当前悬停的Y值,利用Rechart组件的鼠标事件捕获数据点信息,动态更新顶部展示内容。

修改后的完整代码

import { useState } from 'react';
import { ResponsiveContainer, LineChart, CartesianGrid, XAxis, YAxis, Tooltip, Line } from 'recharts';

const StockChart = ({ data, low, high }) => {
  // 存储当前悬停的close值
  const [hoveredValue, setHoveredValue] = useState(null);

  return (
    <>
      <h3>Stock</h3>
      {/* 动态展示悬停值,无悬停时显示默认提示 */}
      <h3>{hoveredValue ? `$${hoveredValue.toFixed(2)}` : 'Hover over the chart'}</h3>
      <div className="chartContainer">
        <ResponsiveContainer width="100%" height="100%">
          <LineChart
            width={800}
            height={250}
            data={data}
            margin={{
              top: 5,
              right: 30,
              left: 20,
              bottom: 5,
            }}
          >
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="date" tick={false} />
            <YAxis dataKey="close" tick={false} domain={[low, high]} />
            <Tooltip />
            <Line 
              type="monotone" 
              dataKey="close" 
              stroke="turquoise" 
              activeDot={{ r: 4 }}
              // 鼠标进入数据点时更新状态
              onMouseEnter={(event) => setHoveredValue(event.payload.close)}
              // 鼠标离开时清空状态
              onMouseLeave={() => setHoveredValue(null)}
            />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </>
  );
};

关键修改点

  • 引入useState创建状态变量hoveredValue,用于保存当前悬停数据点的Y值(即close字段)
  • 将原固定文本替换为动态渲染内容:有悬停值时格式化显示(保留两位小数并添加$符号),无悬停时显示提示文本
  • 给Line组件绑定onMouseEnter和onMouseLeave事件,分别触发状态更新与清空,精准捕获每个数据点的鼠标交互

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:06:50