第一步:创建 echarts 图表项目
App.js根组件
import EchartsCom from './components/EchartsCom'
function App() {
return (
<div className="App">
<EchartsCom></EchartsCom>
</div>
)
}
export default App
index.js入口
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root')
)
第二步:在终端下两个包
yarn add echarts echarts-for-react 或 npm i echarts echarts-for-react
第三步:组件 EchartsCom.js 中引入
import ReactEcharts from 'echarts-for-react'
第四步:定义 echarts 配置项,传递 option
- 官网复制一个自己喜欢的实例的代码
- 定义变量接收配置项
- return
<ReactEcharts option={配置的option}><ReactEcharts>
EchartsCom.js
import React from 'react'
// 1.引入
import ReactEcharts from 'echarts-for-react'
const EchartsCom = () => {
// 2.官网复制过来的 echarts 配置实例
const option = {
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [
{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '40',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}
]
};
// 3.return 一个组件,传入配置项作为 option 的属性值
return <div>
<ReactEcharts option={option}></ReactEcharts>
</div>
}
export default EchartsCom
第五步:代码优化
- 抽离
option配置项作为单独的 js 文件并导出 - 组件 EchartsCom.js 导入
option,并在 return 的组件中携带
option.js
const option = {
tooltip: {
trigger: 'item'
},
legend: {
top: '5%',
left: 'center'
},
series: [
{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '40',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}
]
}
export default option
EchartsCom.js
import React from 'react'
// 1.引入
import ReactEcharts from 'echarts-for-react'
// 2.导入 option
import option from './option'
const EchartsCom = () => {
// 3.return 一个组件,传入配置项作为 option 的属性值
return <div>
<ReactEcharts option={option}></ReactEcharts>
</div>
}
export default EchartsCom