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

ReactJS中如何自动生成基于指定列的折线图(附表格代码)

实现AgGrid表格下方自动生成指定列的折线图

现有代码

列配置

const foodData = [ 
    { headerName: "Cake", field: "cake" }, 
    { headerName: "Sweets", field: "sweets" }, 
    { headerName: "Savoury", field: "savoury" }, 
];

表格组件

return ( 
  <div className="Foods"> 
    <SearchBar onSubmit={setSearch} />
    <div 
       className="ag-theme-balham" 
       style={{ 
          height: "300px", 
          width: "1160px" 
       }} 
    > 
        <AgGridReact
          columnDefs={foodData} 
          rowData={rowData}
        /> 
    </div> 
  </div> 
);

需求

在表格下方自动生成仅基于Sweets和Savoury两列数据的折线图,无需手动选择行。

实现步骤及代码

1. 安装图表依赖

选用react-chartjs-2(基于Chart.js)实现折线图,先安装依赖:

npm install react-chartjs-2 chart.js

2. 修改组件代码

导入图表组件,处理数据源生成图表所需格式,最后在表格下方渲染折线图:

import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from 'chart.js';

// 注册Chart.js核心组件
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

function FoodsComponent() {
  const foodData = [ 
      { headerName: "Cake", field: "cake" }, 
      { headerName: "Sweets", field: "sweets" }, 
      { headerName: "Savoury", field: "savoury" }, 
  ];

  // 从rowData中提取折线图所需数据
  const chartData = {
    // x轴标签:用行序号标识,可替换为rowData中的其他字段(如日期、名称)
    labels: rowData.map((_, idx) => `行 ${idx + 1}`),
    datasets: [
      {
        label: 'Sweets',
        data: rowData.map(item => item.sweets),
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.1)',
        tension: 0.1
      },
      {
        label: 'Savoury',
        data: rowData.map(item => item.savoury),
        borderColor: 'rgb(53, 162, 235)',
        backgroundColor: 'rgba(53, 162, 235, 0.1)',
        tension: 0.1
      }
    ]
  };

  // 图表自定义配置
  const chartOptions = {
    responsive: true,
    plugins: {
      legend: { position: 'top' },
      title: { display: true, text: 'Sweets与Savoury趋势对比' }
    },
    scales: { y: { beginAtZero: true } }
  };

  return ( 
    <div className="Foods"> 
      <SearchBar onSubmit={setSearch} />
      <div 
         className="ag-theme-balham" 
         style={{ height: "300px", width: "1160px" }} 
      > 
          <AgGridReact columnDefs={foodData} rowData={rowData} /> 
      </div>
      {/* 折线图容器,与表格宽度保持一致 */}
      <div style={{ marginTop: '20px', width: '1160px' }}>
        <Line data={chartData} options={chartOptions} />
      </div>
    </div> 
  );
}

export default FoodsComponent;

说明

  • 数据处理:通过rowData.map批量提取目标列数据,x轴标签可根据业务需求替换为rowData中的实际标识字段(如日期、产品名)
  • 样式自定义:可通过chartOptions调整图表标题、图例位置、坐标轴规则等
  • 布局适配:折线图容器宽度与表格保持一致,避免页面布局错乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:55:23