echarts 饼图移动端_react+echarts实现饼图
时间: 2023-10-14 17:15:14 浏览: 55
首先,你需要在 React 项目中安装 echarts:
```
npm install echarts --save
```
然后,在需要使用饼图的组件中引入 echarts,并在组件的生命周期函数 `componentDidMount` 中初始化 echarts 实例,并使用数据渲染饼图。
例如,以下是一个简单的饼图组件的代码:
```
import React, { Component } from 'react';
import echarts from 'echarts';
class PieChart extends Component {
componentDidMount() {
this.initChart();
}
initChart = () => {
const { data } = this.props;
const chart = echarts.init(this.chartRef);
chart.setOption({
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)',
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center',
},
emphasis: {
label: {
show: true,
fontSize: '30',
fontWeight: 'bold',
},
},
labelLine: {
show: false,
},
data,
},
],
});
};
render() {
return (
<div
ref={(ref) => {
this.chartRef = ref;
}}
style={{ width: '100%', height: '300px' }}
/>
);
}
}
export default PieChart;
```
在上面的代码中,我们使用 `componentDidMount` 函数初始化 echarts 实例,并使用传递进来的数据渲染饼图。注意,我们在组件的 `render` 函数中返回一个 `div` 元素,这个元素的 `ref` 属性绑定了一个回调函数,用来获取这个元素的引用,以便后续使用 echarts 来渲染图表。
在父组件中,我们可以使用以下代码来渲染这个饼图组件:
```
import React, { Component } from 'react';
import PieChart from './PieChart';
class App extends Component {
state = {
data: [
{ value: 335, name: '直接访问' },
{ value: 310, name: '邮件营销' },
{ value: 234, name: '联盟广告' },
{ value: 135, name: '视频广告' },
{ value: 1548, name: '搜索引擎' },
],
};
render() {
const { data } = this.state;
return (
<div>
<PieChart data={data} />
</div>
);
}
}
export default App;
```
在父组件中,我们传递一个 `data` 属性给饼图组件,这个属性包含了用于渲染饼图的数据。最终,我们可以在页面中看到一个简单的饼图。