react-google-charts GeoChart选中区域无法保持高亮问题求助
解决react-google-charts GeoChart点击区域无法保持高亮的问题
问题原因
你的代码仅监听了select事件打印选中区域,但没有持久化选中状态,且未对选中区域的样式进行自定义绑定。React组件重新渲染时,图表的临时选中状态会被重置;同时GeoChart默认的选中高亮并非持久化机制,需要主动通过状态管理+样式绑定来实现。
解决方案(类组件版本)
通过React状态保存选中行索引,添加style角色列自定义高亮样式,并在图表就绪时恢复选中状态,实现点击后区域保持高亮直到下一次点击:
import React, { Component } from "react"; import Chart from "react-google-charts"; class GeoChartComponent extends Component { state = { selectedRow: null, chartData: [ ["Country", "Popularity", { role: "style" }], ["Germany", 200, ""], ["United States", 300, ""], ["Brazil", 400, ""], ["Canada", 500, ""], ["France", 600, ""], ["RU", 700, ""], ["India", 900, ""] ] }; handleChartSelect = ({ chartWrapper }) => { const chart = chartWrapper.getChart(); const selection = chart.getSelection(); if (selection.length === 0) { // 清除所有选中样式 const updatedData = this.state.chartData.map(row => { if (row[2]) row[2] = ""; return row; }); this.setState({ selectedRow: null, chartData: updatedData }); return; } const selectedRowIndex = selection[0].row; // 更新数据,为选中区域绑定高亮样式 const updatedData = this.state.chartData.map((row, index) => { if (index === 0) return row; // 跳过表头行 const isSelected = (index - 1) === selectedRowIndex; return [ row[0], row[1], isSelected ? "fill-color: #e7711b; stroke-color: #a63d00;" : "" ]; }); this.setState({ selectedRow: selectedRowIndex, chartData: updatedData }); const region = this.state.chartData[selectedRowIndex + 1][0]; console.log("Selected : " + region); }; render() { return ( <div> <Chart chartEvents={[ { eventName: "select", callback: this.handleChartSelect }, { eventName: "ready", callback: ({ chartWrapper }) => { // 组件加载/更新时恢复之前的选中状态 if (this.state.selectedRow !== null) { const chart = chartWrapper.getChart(); chart.setSelection([{ row: this.state.selectedRow }]); } } } ]} chartType="GeoChart" width="100%" height="400px" data={this.state.chartData} options={{ enableRegionInteractivity: true, tooltip: { isHtml: true } }} /> </div> ); } } export default GeoChartComponent;
关键实现点
- 状态持久化:用
selectedRow状态保存选中行的索引,确保组件重绘时选中状态不丢失。 - 自定义高亮样式:在数据中添加
style角色列,通过修改该列的值为选中区域设置填充色和边框色。 - 恢复选中状态:在
ready事件中调用chart.setSelection(),确保组件初始化或更新后,之前的选中区域能重新高亮。
内容的提问来源于stack exchange,提问作者krushnakantL
相关产品推荐
相关产品推荐

