直接在react中使用原生的方法

  1. // 引入 ECharts 主模块
  2. import echarts from 'echarts/lib/echarts';
  3. // // 引入提示框和标题组件
  4. import 'echarts/lib/component/tooltip';
  5. import 'echarts/lib/component/title';
  6. import 'echarts/lib/component/legend'
  7. import 'echarts/lib/chart/pie';
  8. const Model_echarts = (props) => {
  9. let [main , setMain] = useState('')
  10. const option = {
  11. title: {
  12. text: '某站点用户访问来源',
  13. subtext: '纯属虚构',
  14. left: 'center'
  15. },
  16. tooltip: {
  17. trigger: 'item',
  18. formatter: '{a} <br/>{b} : {c} ({d}%)'
  19. },
  20. legend: {
  21. orient: 'vertical',
  22. left: 'left',
  23. data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  24. },
  25. series: [
  26. {
  27. name: '访问来源',
  28. type: 'pie',
  29. radius: '55%',
  30. center: ['50%', '60%'],
  31. data: [
  32. { value: 335, name: '直接访问' },
  33. { value: 310, name: '邮件营销' },
  34. { value: 234, name: '联盟广告' },
  35. { value: 135, name: '视频广告' },
  36. { value: 1548, name: '搜索引擎' }
  37. ],
  38. emphasis: {
  39. itemStyle: {
  40. shadowBlur: 10,
  41. shadowOffsetX: 0,
  42. shadowColor: 'rgba(0, 0, 0, 0.5)'
  43. }
  44. }
  45. }
  46. ]
  47. };
  48. useEffect(()=>{
  49. var node = document.getElementById('main')
  50. setMain(node)
  51. } , [])
  52. // 基于准备好的dom,初始化echarts实例
  53. if(main !== ""){
  54. var myChart = echarts.init(main);
  55. myChart.resize({ height: '400px' })
  56. myChart.setOption(option);
  57. }
  58. // 绘制图表
  59. return ( <div id="main"></div> )
  60. }

使用echarts-for-react控件

对于组件来说,只有一个API——getEchartsInstance(),用来获取Echarts的实例对象。获取到对象后就可以使用任意的Echarts API。

  1. // render the echarts component below with rel
  2. <ReactEcharts ref={(e) => { this.echarts_react = e }}
  3. option={this.getOption()} />
  4. let echarts_instance = this.echarts_react.getEchartsInstance();
  5. // then you can use any API of echarts.
  6. let base64 = echarts_instance.getDataURL();
  7. 或者写成函数组件的形式
  8. <ReactEcharts ref={e => echartRef.current = e } option={options} />
  9. let chartInstance = echartRef.current.getEchartsInstance()
  10. chartInstance.resize({ height: '100%' })
  11. // then get the `ReactEcharts` use this.echarts_react