【问题标题】:Click Event not working on Recharts Pie Label单击事件不适用于 Recharts 饼图标签
【发布时间】: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


    【解决方案1】:

    Rechart 条形图也有这个问题。我通过将自定义标签的 pointerEvents 设置为 none 来解决它。

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

    根据MDN,通过设置pointer-events: none

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

    因此点击事件通过标签并触发Pie onClick。

    【讨论】:

    • 感谢您的回复@Alex。将尝试此解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2022-01-17
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多