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

如何在React中基于ECharts框选同步过滤双图表数据?

解决图表联动过滤的方案

要实现BarPlot框选后同步过滤两个图表的数据,核心是把选中状态的管理提升到父组件App,让App统一控制两个子组件的数据源,具体步骤如下:

1. 改造App组件,管理选中状态与过滤逻辑

在App中添加状态存储选中的dataIndex,同时根据选中状态动态生成过滤后的数据:

import { useState } from 'react';

function App() {
  // 存储选中的dataIndex数组,初始为空表示全量数据
  const [selectedIndexes, setSelectedIndexes] = useState([]);

  // 根据选中状态过滤数据
  const filteredData = selectedIndexes.length > 0
    ? data.filter((_, index) => selectedIndexes.includes(index))
    : data;

  // 接收BarPlot传递的选中索引
  const handleBrushChange = (indexes) => {
    setSelectedIndexes(indexes);
  };

  return (
    <div>
      <BarPlot data={filteredData} onBrushChange={handleBrushChange} />
      <ScatterPlot data={filteredData} />
    </div>
  );
}

2. 改造BarPlot组件,传递选中状态给父组件

修改BarPlot的onBrushSelected方法,把选中的dataIndex通过回调传给App:

function BarPlot({ data, onBrushChange }) {
  const onBrushSelected = params => {
    const selected = params.batch[0].selected;
    // 获取所有选中项的dataIndex,组成数组
    const selectedIndexes = selected[0].dataIndex;
    // 调用父组件的回调传递选中索引
    onBrushChange(selectedIndexes);
  };

  // 剩余配置代码保持不变
  const option = {
    dataset: {
      source: data,
    },
    xAxis: {},
    yAxis: { type: 'category' },
    series: [
      {
        type: 'bar',
        encode: {
          x: 'amount',
          y: 'product',
        },
      },
    ],
    toolbox: {
      show: true,
    },
    brush: {
      toolbox: ['rect', 'clear'],
      throttleType: 'debounce',
      throttleDelay: 300,
    },
  };

  const onEvents = {
    brushselected: onBrushSelected,
  };

  return (
    <ReactEChartsCore echarts={echarts} option={option} onEvents={onEvents} />
  );
}

关键说明

  • 状态提升:把选中状态放在父组件App中,确保两个图表组件能共享同一套过滤后的数据源。
  • 回调传递:通过onBrushChange回调,让子组件BarPlot把选中的索引传递给父组件,由父组件统一处理过滤逻辑。
  • 全量/切换逻辑:当没有选中项时(selectedIndexes为空),直接使用原始数据;有选中项时,筛选出对应索引的数据。

内容的提问来源于stack exchange,提问作者psych0groov3

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:55:17