使用 react-apexcharts 的点击事件

Click event with react-apexcharts

我正在使用 react-apexcharts,我想在用户单击其中一个部分后在饼图上添加一个事件。这是我的图表:

<div className="pie">
    <Chart options={{
        labels: [
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
        ],
        theme: {
            monochrome: {
                enabled: false
            }
        },
        responsive: [{
            breakpoint: 480,
            options: {
                chart: {
                    width: "100%"
                },
                legend: {
                    show: false
                }
            }
        }]
    }}
    colors={["#1B2260"]}
    series={[44, 55, 41, 17, 15]}
    labels={["Apple", "Mango", "Orange", "Watermelon"]}
    type="pie"
    width="300" />
</div>

当用户点击 "Apple" 部分时,我要打印 "Apple"。 This 是我能找到的关于点击事件的最佳文档,但我无法让它工作。

任何帮助都会很棒!谢谢

尝试将其添加到您的选项对象中:

chart: {
    events: {
    dataPointSelection: (event, chartContext, config) => { 
        console.log(config.w.config.labels[config.dataPointIndex])}
    }
}

here 是您代码的工作示例

您可以使用 dataPointSelection 单击任何数据点时触发的事件。

根据 apexCharts 上的文档:

dataPointSelection Fires when user clicks on a datapoint (bar/column/marker/bubble/donut-slice). The third argument, in addition to the config object, also includes additional information like which dataPointIndex was selected of which series. If you have allowMultipleDataPointsSelection enabled, the third argument includes selectedDataPoints property to get all selected dataPoints.

在您的情况下,您必须在选项下添加和新建 属性:

chart: {
    events: {
    dataPointSelection: (event, chartContext, config) => { 
        // this will print mango, apple etc. when clicked on respective datapoint
        console.log(config.w.config.labels[config.dataPointIndex])}
    }
}

希望这对您有所帮助,编码愉快