如何在Recharts中实现仅展示鼠标悬停对应折线的Tooltip数据
如何在Recharts中实现仅展示鼠标悬停对应折线的Tooltip数据
我完全懂你现在的困扰——用Recharts做多折线图时,鼠标明明只悬停在其中一条线上,可Tooltip里却把所有折线对应X轴的数据都塞进来了,只想看当前这条线的内容对吧?我之前也遇到过类似的问题,给你分享两个实用的解决办法:
方法一:靠Recharts自带属性快速解决
这个方法最简单,只需要调整两个配置:
- 给Tooltip组件设置
shared={false}:这个属性的作用就是让Tooltip只显示当前悬停的系列数据,而不是所有系列在同一个X轴位置的内容。 - 给每个Line组件加上
activeDot属性:默认情况下Recharts的折线点是隐藏的,鼠标悬停在折线区域时可能会触发整个X轴的Tooltip,加上activeDot后,只有当鼠标悬停在具体的点上时才会触发Tooltip,而且只会显示当前点所属折线的数据。
修改后的代码大概是这样:
<Line type="linear" dataKey="overall_attendance" stroke="#82ca9d" strokeWidth={3} label="Attendance" activeDot={{ r: 6 }} // 开启点交互,r是点的半径 /> <Line type="linear" dataKey="video_watched_percentage" strokeWidth={3} label="Video Watched" activeDot={{ r: 6 }} /> <Tooltip content={<CustomTooltip />} shared={false} />
这时候你再看CustomTooltip里的payload,就只会有当前悬停的那条折线的数据了。
方法二:手动跟踪悬停状态(适合不需要显示点的场景)
如果不想显示折线的点,那我们可以自己跟踪鼠标悬停的是哪条折线,然后在Tooltip里过滤数据:
- 先在父组件里加个状态,用来保存当前悬停的折线dataKey:
import { useState } from 'react'; const YourChartComponent = () => { const [hoveredDataKey, setHoveredDataKey] = useState(null); // 其他代码...
- 给每个Line组件加上鼠标进入和离开的事件,更新这个状态:
<Line type="linear" dataKey="overall_attendance" stroke="#82ca9d" strokeWidth={3} label="Attendance" onMouseEnter={() => setHoveredDataKey("overall_attendance")} onMouseLeave={() => setHoveredDataKey(null)} /> <Line type="linear" dataKey="video_watched_percentage" strokeWidth={3} label="Video Watched" onMouseEnter={() => setHoveredDataKey("video_watched_percentage")} onMouseLeave={() => setHoveredDataKey(null)} />
- 修改CustomTooltip,接收这个状态并过滤payload:
const CustomTooltip = ({ active, payload, label, hoveredDataKey }) => { if (!active || !payload || !hoveredDataKey) return null; // 只保留当前悬停折线的数据 const targetItem = payload.find(item => item.dataKey === hoveredDataKey); if (!targetItem) return null; return ( <div style={{ padding: '8px', backgroundColor: '#fff', border: '1px solid #eee', borderRadius: '4px' }}> <p className="tooltip-label">{`${label}`}</p> <p className="tooltip-value" style={{ color: targetItem.color }}> {`${targetItem.name}: ${targetItem.value}`} </p> </div> ); };
- 最后把状态传给Tooltip的自定义内容:
<Tooltip content={<CustomTooltip hoveredDataKey={hoveredDataKey} />} shared={false} />
这样就实现了和MUI X Charts里item模式一样的效果——鼠标悬停哪条线,Tooltip就只显示哪条线的数据。
备注:内容来源于stack exchange,提问作者Algorithm Unlock
相关产品推荐
相关产品推荐

