单击事件不在Recharts Pie Label上工作

时间:2017-12-21 10:49:58

标签: reactjs onclick pie-chart recharts

我正在使用React Project的 Recharts 插件显示带有2个部分和自定义标签的饼图

我的要求是点击获取饼图部分的值。我可以通过将onClick道具添加到 Pie 标签来实现它。但问题是当我点击PieCharts中的标签时,不会触发点击事件。

有些搜索结果说,我们不能在svg子元素上点击事件,如rect,circle,text等。

有人遇到过这样的问题吗?请帮我解决这个问题。

  

饼图代码

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>
);

}

以下是图表的截图。

Pie Chart

1 个答案:

答案 0 :(得分:1)

我也遇到了Rechart Bar Chart这个问题。我通过将自定义标签的pointerEvents设置为none来解决它。

const renderCustomizedLabel = (...) => {
  ...
  return <g style={{ pointerEvents: 'none' }}>...</g>;
};

根据MDN,设置pointer-events: none

  

元素永远不是鼠标事件的目标;但是,鼠标事件   如果那些后代具有,则可以将其后代元素作为目标   指针事件设置为其他值。在这种情况下,鼠标   事件将触发此父元素上的事件侦听器   适合在活动期间往返于后代的路上   捕获/泡沫阶段。

因此,click事件会通过标签并触发Pie onClick。

相关问题