重图-如何为折线图和条形图提供两种不同的工具提示



当有人将鼠标悬停在行和栏上时,我想有两个不同的工具提示。默认情况下Tooltip组件将两者视为相同,但它们是两种不同类型的数据。这就是为什么我想根据用户悬停的内容为每个工具提示设置一个单独的工具提示。

我试图首先为Line图表解决这个问题,我相信Bar图表也是如此。我正在使用activeDot对象来知道用户悬停在哪个点上。虽然它触发了onMouseOver函数,但它不包含任何数据来知道它是哪个点。我能做些什么来让数据按照内容Tooltip自定义(在我的代码中CustomizedTooltip(。如labelpayload等。

这是我到目前为止所拥有的,CodeSandBox

这里的想法是维护要显示工具提示的图表state

然后更新状态onMouseOver并在onMouseLeave上重置状态。

请在代码沙盒找到您的更新代码

import * as React from "react";
import { render } from "react-dom";
import {
ResponsiveContainer,
ComposedChart,
Line,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend
} from "recharts";
const data = [
{ name: "" },
{ name: "Monday", uv: 265, pv: 800 },
{ name: "Tuesday", uv: 475, pv: 967 },
{ name: "Wednesday", uv: 624, pv: 1098 },
{ name: "Thursday", uv: 856, pv: 1200 },
{ name: "Friday", uv: 1024, pv: 1108 },
{ name: "Saturday", uv: 1116, pv: 1220 },
{ name: "Sunday", uv: 1208, pv: 1358 },
{ name: "" }
];
const formatter = (value: string) => `$${value}`;
class CustomizedTooltip extends React.PureComponent<any> {
render() {
const { label, payload, active, chartType } = this.props;
if (!active || !label || payload.length === 0) return null;
return (
<div className="i-will-customize-tooltip-later">
<p className="label">{`${label} : ${payload[chartType].value}`}</p>
</div>
);
}
}
class CustomizedDot extends React.PureComponent<any> {
render() {
const { cx, cy, value } = this.props;
if (!value) {
return null;
}
return (
<svg
x={cx - 5}
y={cy - 5}
width={10}
height={10}
viewBox="0 0 10 10"
fill="#ff7385"
>
<rect width="10" height="10" />
</svg>
);
}
}
class LineBarAreaComposedChart extends React.PureComponent<any, any> {
constructor(){
super({})
this.state = {
chartType: 0
}
}
render() {
return (
<ResponsiveContainer minHeight={500}>
<ComposedChart
width={800}
height={400}
data={data}
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}
>
<CartesianGrid stroke="#efefef" vertical={false} />
<XAxis
dataKey="name"
type="category"
axisLine={false}
tickLine={false}
/>
<YAxis
dataKey="pv"
tickFormatter={formatter}
type="number"
axisLine={false}
tickLine={false}
/>
<Tooltip cursor={false} content={<CustomizedTooltip chartType={this.state.chartType}/>} />
<Legend />
<Bar name="Donation total" dataKey="pv" barSize={80} fill="#48bbee" />
<Line
name="Average dontaion trend"
type="monotone"
dataKey="uv"
data={data}
stroke="#ff7385"
dot={<CustomizedDot />}
activeDot={{
onMouseOver: (e: any) => this.setState({chartType: 1}),
onMouseLeave: (e: any) => this.setState({chartType: 0})
}}
/>
</ComposedChart>
</ResponsiveContainer>
);
}
}
render(<LineBarAreaComposedChart />, document.getElementById("root"));

您可以添加三元运算符(又名条件渲染( 像这样:

<Tooltip cursor={false} content={type===line?<CustomizedTooltip chartType={this.state.chartType}/>:<CustomizedTooltipBar chartType={this.state.chartType}/>} />

最新更新