Sur*_*han 2 onclick pie-chart reactjs recharts
我正在为 React 项目开发Recharts插件来显示饼图。
我的要求是在单击时获取饼图部分的值。我可以通过向Pie添加 onClick 道具来实现它标签来实现它。但问题是当我单击饼图中的标签时,未触发单击事件。
一些搜索结果显示,我们不能在 svg 子元素(如矩形、圆形、文本等)上单击事件。
有人遇到过这样的问题吗?请帮助我如何继续进行此操作。
饼图代码
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>
Run Code Online (Sandbox Code Playgroud)
单击事件函数
onPieClick = (index, data) => {
console.log('onPieClick'+index.value);
}
Run Code Online (Sandbox Code Playgroud)
自定义标签代码库
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>
);
Run Code Online (Sandbox Code Playgroud)
}
下面是图表的屏幕截图。
我在重新绘制条形图时也遇到了这个问题。我通过将自定义标签的pointerEvents设置为none来解决这个问题。
const renderCustomizedLabel = (...) => {
...
return <g style={{ pointerEvents: 'none' }}>...</g>;
};
Run Code Online (Sandbox Code Playgroud)
根据MDN,通过设置pointer-events: none
该元素永远不是鼠标事件的目标;但是,如果后代将指针事件设置为某个其他值,则鼠标事件可能会以其后代元素为目标。在这些情况下,鼠标事件将在事件捕获/冒泡阶段期间在往返子元素的途中酌情触发此父元素上的事件侦听器。
因此,点击事件会通过标签并触发 Pie onClick。
| 归档时间: |
|
| 查看次数: |
4307 次 |
| 最近记录: |