4

我正在使用react-chartJs-2库来显示图表。假设,用户点击条形图/甜甜圈图部分,他必须被重定向到特定页面。以下是我为 DoughnutChart 编写的代码:

  1. ChartDisplay.jsx
<div className="DonutChartSection" >
   <Doughnut labelArray = {this.state.labelArr} DataArray = {this.state.DoughnutDataArr} colorArray = {this.state.DoughnutColorArr} title={"Employees"} />
</div>
  1. 甜甜圈.jsx

    import React from 'react';
    import {Doughnut} from 'react-chartjs-2';
    
    Chart.defaults.global.defaultFontStyle = 'Bold';  
    Chart.defaults.global.defaultLegendPosition = 'left';
    
    export default class DoughnutChartView extends React.Component{
      constructor(props) {
         super(props);
         this.state = { };
      }
    
      render() {
        let data = {
            labels: this.props.labelArray,
            datasets: [{
                data: this.props.DataArray,
                backgroundColor: this.props.colorArray,
                hoverBackgroundColor: this.props.colorArray,
            }]
        } 
        return (
          <div>
          <span className="titleName" >{this.props.title}</span> 
            <Doughnut data={data}  />
          </div>
        );
      }
    };
    

我浏览了 github 页面,发现以下事件可用于点击事件,但不知道如何在我的代码中使用它。

https://github.com/jerairrest/react-chartjs-2#onelementsclick--getelementsaevent-function

4

2 回答 2

7

实际上,您实际上已经回答了您的问题:onElementsClick当用户单击图表的元素时,可用于执行操作。onElementsClick是图表本身的一个道具,所以:

<Doughnut data={data} onElementsClick={elems => {
    // if required to build the URL, you can 
    // get datasetIndex and value index from an `elem`:
    console.log(elems[0]._datasetIndex + ', ' + elems[0]._index);
    // and then redirect to the target page:
    window.location = "https://example.com";
}} />

请注意,它elems可能包含多个元素,例如在堆积条形图的情况下(在这种情况下,它包括单击的条形图的所有元素)。

于 2018-09-05T09:17:04.763 回答
1

这是单击饼图的实际快速解决方案

import { Pie } from 'react-chartjs-2'
        <Pie
            getElementAtEvent={(data) => {
                if(data.length >= 1){
                    const dataItem: any  = data[0]
                    const index = dataItem.index
                    const foundLabel = props.labels[index]
                    // redirect or do stuff
                }
            }}
于 2021-06-18T10:35:15.030 回答