Recharts折线图自定义数据点失效:所有点显示为圆形
问题描述
参考Recharts自定义数据点折线图示例,为包含4条折线的图表设置不同数据点形状(矩形、菱形、圆形、三角形),但实现后所有数据点均显示为圆形,不符合预期。相关代码如下:
自定义组件代码
const CustomizedDot = (props) => { const { cx, cy, dataKey } = props; if (dataKey === 'A') { return ( <svg > <rect /> </svg> ); } if (dataKey === 'B') { return ( <svg ""> <polygon points="0 40,40 80,80 40,40 0" /> </svg> ); } if (dataKey === 'C') { return ( <svg > <circle /> </svg> ); } if (dataKey === 'D') { return ( <svg > <polygon points="50 15, 100 100, 0 100"/> </svg> ); } };
折线图生成代码
<LineChart data={data.map((data) => ({ ...data, date: data.date, }))} > <XAxis dataKey="date" /> <YAxis /> <Tooltip /> <Legend /> {(Object.keys(lineConfig) as TimeSeriesMetricKey[]).reduce( (items: React.ReactElement[], key) => { return [ ...items, <Line key={key} dataKey={key} name={lineConfig[key].legendLabel} stroke={lineConfig[key].color} strokeWidth={2} activeDot={{r : 8}} dot={<CustomizedDot />} />, ]; }, [] )} </LineChart>
问题原因及解决方案
1. 自定义组件未接收折线的标识参数
Recharts不会自动把Line组件的dataKey传递给dot组件,导致CustomizedDot内的dataKey始终为undefined,所有条件判断都不生效,最终Recharts渲染了默认的圆形数据点。
2. SVG元素缺少必要的定位与尺寸属性
自定义组件中的矩形、多边形、圆形都未设置定位(如cx/cy、x/y)和尺寸(如r、width/height),即便条件判断生效,这些形状也无法在正确位置显示。此外第二个svg标签存在语法错误(多余的""),会导致组件渲染异常。
3. 未传递数据点的中心坐标给SVG元素
CustomizedDot接收了cx、cy参数,但未传递给内部的SVG图形元素,导致自定义形状无法对齐到数据点的正确位置。
修正后的代码
自定义组件
const CustomizedDot = (props) => { const { cx, cy, r = 6, seriesKey } = props; const size = r * 2; switch(seriesKey) { case 'A': return ( <svg width={size} height={size} x={cx - r} y={cy - r}> <rect width={size} height={size} fill="currentColor" /> </svg> ); case 'B': return ( <svg width={size} height={size} x={cx - r} y={cy - r}> <polygon points={`${r} 0, ${size} ${r}, ${r} ${size}, 0 ${r}`} fill="currentColor" /> </svg> ); case 'C': return ( <svg width={size} height={size} x={cx - r} y={cy - r}> <circle cx={r} cy={r} r={r} fill="currentColor" /> </svg> ); case 'D': return ( <svg width={size} height={size} x={cx - r} y={cy - r}> <polygon points={`${r} 0, ${size} ${size}, 0 ${size}`} fill="currentColor" /> </svg> ); default: return <circle cx={cx} cy={cy} r={r} fill="currentColor" />; } };
折线图部分
修改Line组件的dot属性,将当前折线的dataKey作为seriesKey传递给自定义组件:
<Line key={key} dataKey={key} name={lineConfig[key].legendLabel} stroke={lineConfig[key].color} strokeWidth={2} activeDot={{r : 8}} dot={<CustomizedDot seriesKey={key} />} />
内容的提问来源于stack exchange,提问作者hetal gohel
相关产品推荐
相关产品推荐

