[英]How to redirect user when clicking on a Chart element
我正在使用react-chartJs-2庫來顯示圖表。 假設,用戶點擊條形圖/甜甜圈圖部分,他必須被重定向到特定頁面。 以下是我為 DoughnutChart 所做的代碼:
<div className="DonutChartSection" >
<Doughnut labelArray = {this.state.labelArr} DataArray = {this.state.DoughnutDataArr} colorArray = {this.state.DoughnutColorArr} title={"Employees"} />
</div>
Doughnut.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--getelementsatevent-function
實際上,您實際上已經回答了您的問題: 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
可能包含多個元素,例如在堆積條形圖的情況下(在這種情況下,它包括單擊的條形圖的所有元素)。
這是單擊餅圖的實際快速解決方案
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
}
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.