import React, { PureComponent } from 'react'; import G2 from 'g2'; import { Row, Col } from 'antd'; import equal from '../equal'; import styles from './index.less'; /* eslint react/no-danger:0 */ class Radar extends PureComponent { state = { legendData: [], } componentDidMount() { this.renderChart(this.props.data); } componentWillReceiveProps(nextProps) { if (!equal(this.props, nextProps)) { this.renderChart(nextProps.data); } } componentWillUnmount() { if (this.chart) { this.chart.destroy(); } } handleRef = (n) => { this.node = n; } handleLegendClick = (item, i) => { const newItem = item; newItem.checked = !newItem.checked; const { legendData } = this.state; legendData[i] = newItem; if (this.chart) { const filterItem = legendData.filter(l => l.checked).map(l => l.name); this.chart.filter('name', filterItem); this.chart.repaint(); } this.setState({ legendData, }); } renderChart(data) { const { height = 0, hasLegend = true, fit = true, tickCount = 4, margin = [16, 30, 16, 30] } = this.props; const colors = ['#1890FF', '#FACC14', '#2FC25B']; if (!data || (data && data.length < 1)) { return; } // clean this.node.innerHTML = ''; const chart = new G2.Chart({ container: this.node, forceFit: fit, height: height - 22, plotCfg: { margin, }, }); this.chart = chart; chart.source(data, { value: { min: 0, tickCount, }, }); chart.coord('polar'); chart.legend(false); chart.axis('label', { line: null, }); chart.axis('value', { grid: { type: 'polygon', }, }); chart.line().position('label*value').color('name', colors); chart.point().position('label*value').color('name', colors).shape('circle'); chart.render(); if (hasLegend) { const geom = chart.getGeoms()[0]; // 获取所有的图形 const items = geom.getData(); // 获取图形对应的数据 const legendData = items.map((item) => { /* eslint no-underscore-dangle:0 */ const origin = item._origin; const result = { name: origin[0].name, color: item.color, checked: true, value: origin.reduce((p, n) => p + n.value, 0), }; return result; }); this.setState({ legendData, }); } } render() { const { height, title, hasLegend } = this.props; const { legendData } = this.state; return (
{ title &&

{title}

}
{ hasLegend && ( { legendData.map((item, i) => ( this.handleLegendClick(item, i)} >

{item.name}

{item.value}
{ i !== (legendData.length - 1) &&
}
)) } ) }
); } } export default Radar;