react使用函数方法画一个antv g2plot的折柱图,并且带有slider,
时间: 2024-02-21 11:01:36 浏览: 162
好的,首先需要引入相关的依赖包:
```javascript
import React, { useState, useEffect } from 'react';
import { Slider } from 'antd';
import { Line, Column } from '@ant-design/charts';
```
然后定义一个函数组件,接收数据作为props:
```javascript
const G2PlotDemo = (props) => {
const { data } = props;
const [sliderValue, setSliderValue] = useState(0); // slider的值
const [lineData, setLineData] = useState([]); // 折线图的数据
const [columnData, setColumnData] = useState([]); // 柱状图的数据
// 根据slider的值筛选数据
useEffect(() => {
const filteredData = data.filter((item) => item.x <= sliderValue);
const lineChartData = filteredData.map((item) => ({ x: item.x, y: item.y1 }));
const columnChartData = filteredData.map((item) => ({ x: item.x, y: item.y2 }));
setLineData(lineChartData);
setColumnData(columnChartData);
}, [sliderValue, data]);
// 定义slider的onChange方法
const handleSliderChange = (value) => {
setSliderValue(value);
};
// 定义折线图的配置项
const lineConfig = {
data: lineData,
xField: 'x',
yField: 'y',
};
// 定义柱状图的配置项
const columnConfig = {
data: columnData,
xField: 'x',
yField: 'y',
};
return (
<div>
<Slider min={0} max={10} defaultValue={0} onChange={handleSliderChange} />
<Line {...lineConfig} />
<Column {...columnConfig} />
</div>
);
};
export default G2PlotDemo;
```
接下来,调用该组件并传入数据即可:
```javascript
const data = [
{ x: 0, y1: 20, y2: 10 },
{ x: 1, y1: 30, y2: 20 },
{ x: 2, y1: 40, y2: 30 },
{ x: 3, y1: 50, y2: 40 },
{ x: 4, y1: 60, y2: 50 },
{ x: 5, y1: 70, y2: 60 },
{ x: 6, y1: 80, y2: 70 },
{ x: 7, y1: 90, y2: 80 },
{ x: 8, y1: 100, y2: 90 },
{ x: 9, y1: 110, y2: 100 },
{ x: 10, y1: 120, y2: 110 },
];
<G2PlotDemo data={data} />
```
这样就完成了一个带有slider、折线图和柱状图的可交互数据可视化组件。
阅读全文