(React js) Как получить название бара, кликнувшего на сгруппированной гистограмме - PullRequest
2 голосов
/ 09 июня 2019

У меня есть Сгруппированная диаграмма Barchart , построенная с использованием response-chartjs-2 , и я хочу получить имя бара, по которому щелкнули.

Iтакже у меня есть Normal Barchart , и я могу получить индекс того бара, на котором я нажал.Я могу добиться этого, используя обработчик события onClick

 return(
         <div className='chart'>
            <Bar 
            data={data}
            width={600}
          height={400}
            options={
              {
              title:{
                display:this.props.displayTitle,
                text: this.props.name+` (${this.props.Total})`,
                fontSize:20
              },
              legend:{
               display:this.props.displayLegend,
               position:this.props.legendPosition
             },
             onClick: this.props.handleClick,
            } 
        }

            />
         </div>
      )

, и моя функция handleClick выглядит следующим образом

handleClick = (event, arr, value) => {
        if (Array.isArray(arr) && arr.length > 0) {
            let [data] = arr
            let i = data._index
            let l = data._chart.tooltip._data.labels
            let key = data._chart.tooltip._data.datasets[0].key
            this.setState({ key: key, index: i, label: l[i], showPopup:true })
        }
    }

, и это массив, который я получаю из функции handleClick

(1) […]
​
0: {…}
​​
_chart: {…}
​​​
"$plugins": Object { descriptors: (3) […], id: 3 }
​​​
_bufferedRender: false
​​​
_bufferedRequest: null
​​​
_listeners: Object { mousemove: listener(), mouseout: listener(), click: listener(), … }
​​​
active: Array []
​​​
animating: false
​​​
aspectRatio: 1.5
​​​
boxes: Array(4) [ {…}, {…}, {…}, … ]
​​​
canvas: <canvas class="chartjs-render-monitor" height="357" width="536" style="display: block; width: 536px; height: 357px;">
​​​
chart: Object { id: 1, width: 536, height: 357, … }
​​​
chartArea: Object { left: 3, top: 44, right: 533, … }
​​​
config: Object { type: "bar", data: {…}, options: {…}, … }
​​​
controller: Object { id: 1, width: 536, height: 357, … }
​​​
ctx: CanvasRenderingContext2D { mozTextStyle: "bold 20px \"Helvetica Neue\", \"Helvetica\", \"Arial\", sans-serif", mozImageSmoothingEnabled: true, globalAlpha: 1, … }
​​​
currentDevicePixelRatio: 1
​​​
data: 
​​​
height: 357
​​​
id: 1
​​​
lastActive: Array []
​​​
legend: Object { doughnutMode: false, fullWidth: true, position: "right", … }
​​​
options: Object { defaultColor: "rgba(0,0,0,0.1)", defaultFontColor: "#666", defaultFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", … }
​​​
scales: Object { "x-axis-0": {…}, "y-axis-0": {…} }
​​​
titleBlock: Object { fullWidth: true, position: "top", weight: 2000, … }
​​​
tooltip: {…}
​​​​
_active: Array []
​​​​
_chart: Object { id: 1, width: 536, height: 357, … }
​​​​
_chartInstance: Object { id: 1, width: 536, height: 357, … }
​​​​
_data: {…}
​​​​​
datasets: Array [ {…} ]
​​​​​
labels: (4) […]
​​​​​​
0: "Low"
​​​​​​
1: "High"
​​​​​​
2: "Medium"
​​​​​​
3: "Urgent"
​​​​​​
length: 4
​​​​​​
<prototype>: Array []
​​​​​
options: Object { scales: {…} }
​​​​​
<prototype>: Object { … }
​​​​
_eventPosition: Object { x: 322, y: 294 }
​​​​
_lastActive: Array []
​​​​
_model: Object { xPadding: 6, yPadding: 6, xAlign: "right", … }
​​​​
_options: Object { enabled: true, mode: "nearest", position: "average", … }
​​​​
_start: null
​​​​
_view: Object { xPadding: 6, yPadding: 6, xAlign: "right", … }
​​​​
<prototype>: Object { constructor: ChartElement(), initialize: initialize(), getTitle: getTitle(), … }
​​​
width: 536
​​​
<get data()>: function get()
​​​
<set data()>: function set()
​​​
<prototype>: Object { construct: construct(), initialize: initialize(), clear: clear(), … }
​​
_datasetIndex: 0
​​
_index: 2
​​
_model: Object { backgroundColor: "rgb(237, 86, 27)", borderColor: "rgba(0,0,0,0.1)", borderSkipped: "bottom", … }
​​
_start: null
​​
_view: Object { backgroundColor: "rgb(237, 86, 27)", borderColor: "rgba(0,0,0,0.1)", borderSkipped: "bottom", … }
​​
_xScale: Object { id: "x-axis-0", type: "category", hidden: false, … }
​​
_yScale: Object { id: "y-axis-0", type: "linear", hidden: false, … }
​​
hidden: false
​​
<prototype>: Object { constructor: ChartElement(), draw: draw(), height: height(), … }
​
length: 1
​
<prototype>: Array []

Здесь я могу получить имя, сначала получив индекс (то есть «_index» из массива) и получив доступ к имени через метку [_index].Эта логика прекрасно работает при работе с Normal Barchart .Но когда мы берем график Grouped Barchart , где каждый период по оси X имеет несколько баров;я снова могу получить значение периода (то есть «_index»).Как получить доступ к определенному индексу бара в наборе сгруппированных столбцов.

...