【发布时间】:2018-04-03 13:08:30
【问题描述】:
我正在为 React 项目开发 Recharts 插件,以显示具有 2 个部分和自定义标签的 饼图。
我的要求是在点击时获取饼图部分的值。我可以通过将 onClick 道具添加到 Pie 标签来实现它。但问题是当我点击饼图中的标签时,点击事件没有被触发。
一些搜索结果说,我们不能在 svg 子元素(如 rect、circle、text 等)上设置 click 事件。
有人遇到过这样的问题吗?请帮我解决这个问题。
饼图代码
const data = [{ name: 'On Time', value: Number(70), mode: 'total' },
{ name: 'Delayed', value: Number(30), mode: 'total' }];
const COLORS = ['#008000', '#fa833c'];
<PieChart width={300} height={300} className={'mainPie'}>
<Pie dataKey="value"
activeIndex={this.state.activeIndex}
labelLine={false}
label={renderCustomizedLabel}
data={data}
cx={150}
cy={130}
outerRadius={120}
innerRadius={60}
onClick={this.onPieClick}
fill="#8884d8">
{data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/>)}
</Pie>
</PieChart>
点击事件函数
onPieClick = (index, data) => {
console.log('onPieClick'+index.value);
}
自定义标签代码库
const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent, index, mode}) => {
let radius = innerRadius + (outerRadius - innerRadius) * 0.3;
let x = cx + radius * Math.cos(-midAngle * (Math.PI / 180));
let y = cy + radius * Math.sin(-midAngle * (Math.PI / 180));
return (
(<g>
<text x={cx} y={cy} dy={8} textAnchor="middle" fill="black" fontSize="12">DELIVERIES</text>
<text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} fontSize="12" dominantBaseline="central">
{(percent * 100).toFixed(2)}%
</text>
</g>
);
}
下面是图表截图。
【问题讨论】:
标签: reactjs onclick pie-chart recharts