You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-google-charts中setSelection使用问题:双图表选中同步实现

解决方案

你遇到的问题核心是onLoad回调返回的是ChartWrapper对象,而非原生Google Charts图表实例,只有调用chartWrapper.getChart()拿到的实例才具备setSelection方法。以下是实现两个图表选中同步的具体步骤:

  1. 定义状态保存两个图表的原生实例
  2. 在onLoad回调中通过getChart()获取并保存实例
  3. 在任意一个图表的select事件中,获取选中项并调用另一个图表的setSelection同步状态

代码示例

import { useState } from 'react';
import { Chart } from 'react-google-charts';

const SyncCharts = () => {
  const [chart1Instance, setChart1Instance] = useState(null);
  const [chart2Instance, setChart2Instance] = useState(null);

  // 示例数据,根据实际场景替换
  const chartData1 = [
    ['Year', 'Sales'],
    ['2019', 1000],
    ['2020', 1170],
    ['2021', 660],
    ['2022', 1030]
  ];

  const chartData2 = [
    ['Year', 'Expenses'],
    ['2019', 400],
    ['2020', 460],
    ['2021', 1120],
    ['2022', 540]
  ];

  const handleChartSelect = (targetChart, sourceSelection) => {
    if (targetChart) {
      targetChart.setSelection(sourceSelection);
    }
  };

  return (
    <div style={{ display: 'flex', gap: '20px' }}>
      <Chart
        chartType="ColumnChart"
        width="500px"
        height="300px"
        data={chartData1}
        onLoad={(chartWrapper) => {
          setChart1Instance(chartWrapper.getChart());
        }}
        chartEvents={[
          {
            eventName: 'select',
            callback: ({ chartWrapper }) => {
              const selection = chartWrapper.getChart().getSelection();
              handleChartSelect(chart2Instance, selection);
            }
          }
        ]}
      />

      <Chart
        chartType="ColumnChart"
        width="500px"
        height="300px"
        data={chartData2}
        onLoad={(chartWrapper) => {
          setChart2Instance(chartWrapper.getChart());
        }}
        chartEvents={[
          {
            eventName: 'select',
            callback: ({ chartWrapper }) => {
              const selection = chartWrapper.getChart().getSelection();
              handleChartSelect(chart1Instance, selection);
            }
          }
        ]}
      />
    </div>
  );
};

export default SyncCharts;

关键说明

  • onLoad回调的参数是ChartWrapper,必须通过getChart()获取原生Google Charts实例,该实例才包含setSelection方法
  • 调用setSelection前要判断目标图表实例是否存在,避免图表未加载完成时触发报错
  • setSelection接收的参数格式与getSelection返回的格式一致,都是包含row/column属性的对象数组

内容的提问来源于stack exchange,提问作者Adam Janáček

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 17:15:14