#reactjs #recharts
#reactjs #повторное использование
Вопрос:
Проблема:
Я создал компонент react, и там я использую recharts. Я создал пользовательский компонент всплывающей подсказки. Там я проверяю условие с помощью метки. Но оно отображается на ярлыке в виде чисел, а не в виде имени, которое я предоставляю в наборе данных. Может ли кто-нибудь помочь мне решить эту проблему?
Вот как выглядит мой код.
import React, { Component } from "react";
import {
BarChart,
Tooltip,
Bar,
Legend,
ResponsiveContainer,
Cell
} from "recharts";
import { Card, CardTitle, CardBody } from "reactstrap";
import "./SessionDuration.css";
const colors = ["#26a0a7", "#79d69f", "#f9ec86", "#ec983d"];
const data = [
{
name: "Page A",
pv: 2400,
amt: 2400
},
{
name: "Page B",
pv: 1398,
amt: 2210
},
{
name: "Page C",
pv: 9800,
amt: 2290
},
{
name: "Page D",
pv: 3908,
amt: 2000
}
];
const CustomTooltip = ({ active, payload, label }) => {
if (active) {
return (
<div className="custom-tooltip">
<p className="label">{`${label} : ${payload[0].value}`}</p>
<p className="intro">{getIntroOfPage(label)}</p>
<p className="desc">Anything you want can be displayed here.</p>
</div>
);
}
return null;
};
const getIntroOfPage = label => {
if (label === "Page A") {
return "Page A is about men's clothing";
}
if (label === "Page B") {
return "Page B is about women's dress";
}
if (label === "Page C") {
return "Page C is about women's bag";
}
if (label === "Page D") {
return "Page D is about household goods";
}
};
class SessionDuration extends Component {
render() {
return (
<Card className="session-duration-card">
<CardTitle className="session-duration-card-header">
Session Duration
</CardTitle>
<CardBody>
<ResponsiveContainer width="100%" height="100%" aspect={4.0 / 5.5}>
<BarChart
data={data}
margin={{
top: 10,
right: 5,
left: 5,
bottom: 5
}}
barGap={10}
>
<Tooltip content={<CustomTooltip />} />
<Bar dataKey="pv" fill="#8884d8">
{data.map((entry, index) => (
<Cell key={`cell-${index}`} fill={colors[index]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</CardBody>
</Card>
);
}
}
export default SessionDuration;
Ответ №1:
В CustomTooltip есть проблема a, которая не получает метку. Итак, вам нужно передать метку там, ниже приведен пример
<Tooltip content={<CustomTooltip label={name} />} />
//Below is small sample of your code that is working fine
[Codepen] https://codepen.io/dwarka/pen/GeQKXZ