天天看點

eCharts增加圖例(legend)的點選事件--echarts-for-react

1. 功能需求:

使用者點選圖例,進入下鑽頁面。

2. 背景

使用echarts-for-react開發的圖表,echarts的點選事件不能應用與圖例,點選圖例會觸發legendselectchanged事件。圖例選擇與非選中狀态會直接影響到圖表的展示效果,非選中狀态圖例對應的内容不會再圖表内展示。當我點選圖例時,頁面跳轉至下鑽頁面。

3. 解決思路

需要保證點選圖例時,頁面跳轉至下鑽頁面,但是被點選的圖例依然是選中狀态。

當我點選圖例觸發legendselectchanged事件時,除了執行業務方法外,同時需要将目前點選的圖例狀态置為選中狀态。

4. 解決方法

  • 使用echarts-for-react元件的onEvents方法監聽事件
  • ref擷取執行個體
  • 參考echarts-for-react文檔
/* typescript */
-----------------------  手動分割線 -----------------------
// eChart元件
<ReactEcharts
    option={this.props.option} // eCharts的option
    onEvents={this.props.onEvents} // 監聽事件方法
    ref={(e: any) => !!this.props.getEchart && this.props.getEchart(e)} // 擷取eChart元件執行個體
/>

-----------------------  手動分割線 -----------------------   
// onEvents 
public handleEvents = { // 點選圖例,監聽圖例狀态改變事件
    'legendselectchanged': this.handleLegendSelectChanged,
}

public handleLegendSelectChanged = (e: any) => { // 監聽圖例狀态改變事件函數
    /**
     * 此處省略業務處理代碼
     * 包括調整下鑽頁面跟資料請求
     */
    if (!!this.echart) { // this.echart為拿到的圖示執行個體,将點選的圖例置為已選中狀态
      this.echart.dispatchAction({
        type: 'legendSelect',
        name: e.name,
      })
    }
};

-----------------------  手動分割線 -----------------------
// 擷取echarts元件執行個體
public getEchart = (e: any) => {
    if (!!e) {
      this.echart = e.getEchartsInstance();
    }
}
           

繼續閱讀