import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Line } from '@ant-design/plots';
const DemoLine = () => {
const [data, setData] = useState([]);
const config = {
data,//这里后端给的数据 -可以按照下面自己自定义的xy轴来修改数据格式
xField: 'time',//x轴 可以自定义
yField: 'value',//y轴 同理
seriesField: 'category',//带标注 同理
yAxis: {
tickInterval:10,//自定义y轴刻度
},
label: {
style: {
opacity: 0.6,
fontSize: 10,
position: 'top',
},
},
point: {//显示数据点以及显示形状
visible: true,
size: 2,
shape: 'disc',
},
label: {//修改数据点的样式和位置
style: {
opacity: 0.6,
fontSize: 10,
position: 'top',
},
},
color: [ //颜色(如果不写就用官方给的颜色循环使用)
'rgba(216,80,67)',
'rgba(243,188,81)',
'rgba(92,164,97)',
'rgba(105,187,195)',
'rgba(238,116,57)',
'rgba(0,146,250)',
'rgba(221,134,143)',
'rgba(58,150,225)',
'rgba(181,136,243)',
'rgba(240,237,61)',
'rgba(119,115,115)',
],
};
return <Line {...config} />;
};
ReactDOM.render(<DemoLine />, document.getElementById('container'));
后端给的数据跟折线图要的格式不一样进行修改
后端数据举例:数组-对象-n个对象
修改
let list = []
for (let i in props.data[0]) { //这里的props.data可以看作是我上面的那个数据结构的值
for (var key in props.data[0][i]) {
var temp = {}
temp.time = key;
temp.value = props.data[0][i][key];
temp.category = i
list.push(temp)
}
}
console.log(list)
修改过后就拿到了需要的值,直接把折线图config中的data替换为list就可以了哦
为了实时更新变化直接将数据放入useEffect里面把最开始的数据作为依赖项放入,写作
const [data, setData] = useState([]);
useEffect(() => {
let list = []
for (let i in props.data[0]) {
for (var key in props.data[0][i]) {
var temp = {}
temp.time = key;
temp.value = props.data[0][i][key];
temp.category = i
list.push(temp)
}
}
console.log(list)
setData(list)
}, [props]);
完整代码(这是组件 值是父组件传的)
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Line } from '@ant-design/plots';
import qualityScore from '@/models/qualityScore';
const BasicLineChart = (props) => {
const [data, setData] = useState([]);
useEffect(() => {
let list = []
for (let i in props.data[0]) {
for (var key in props.data[0][i]) {
var temp = {}
temp.time = key;
temp.value = props.data[0][i][key];
temp.category = i
list.push(temp)
}
}
console.log(list)
setData(list)
}, [props]);
const config = {
data,
xField: 'time',
yField: 'value',
seriesField: 'category',
yAxis: {
tickInterval:10,
label: {
style: {
fontSize: 12,
},
},
},
color: [
'rgba(216,80,67)',
'rgba(243,188,81)',
'rgba(92,164,97)',
'rgba(105,187,195)',
'rgba(238,116,57)',
'rgba(0,146,250)',
'rgba(221,134,143)',
'rgba(58,150,225)',
'rgba(181,136,243)',
'rgba(240,237,61)',
'rgba(119,115,115)',
],
point: {
visible: true,
size: 2,
shape: 'disc',
},
label: {
style: {
opacity: 0.6,
fontSize: 10,
position: 'top',
},
},
};
return (
<Line
{...config}
style={{ width: '100%', height: '300px', padding: '10px 40px 20px 40px', fontSize: '12px' }}
/>
);
};
export default BasicLineChart;
成品:
展开: