ReactJS集成Echarts绘制折线图页面空白,求排查解决
问题:React中使用ECharts绘制折线图页面空白
我尝试按照ECharts的简单折线图示例实现,但页面显示空白,我的代码如下:
import React, {useState, useEffect} from 'react'; import * as echarts from 'echarts'; export const CreateCharts = () => { function drawCharts(tid) { var chartDom = document.getElementById('chartmain'); var myChart = echarts.init(chartDom); var option; option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [150, 230, 224, 218, 135, 147, 260], type: 'line' } ] }; myChart.setOption(option); } useEffect ( () => { drawCharts(0); }, []); return( <div id="chartmain" key="chartmain"> </div> ); }
烦请帮忙排查我遗漏了什么?
解决方案
页面空白的核心原因是挂载ECharts的DOM容器没有设置宽高,默认空div的宽高为0,导致图表无法渲染。同时可以优化React中DOM元素的获取方式,避免潜在问题。
修改后的代码:
import React, { useEffect, useRef } from 'react'; import * as echarts from 'echarts'; export const CreateCharts = () => { const chartRef = useRef(null); useEffect(() => { if (!chartRef.current) return; const myChart = echarts.init(chartRef.current); const option = { xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [150, 230, 224, 218, 135, 147, 260], type: 'line' } ] }; myChart.setOption(option); // 组件卸载时销毁图表,避免内存泄漏 return () => { myChart.dispose(); }; }, []); return ( <div ref={chartRef} style={{ width: '600px', height: '400px' }} /> ); }
关键修改点:
- 给容器设置明确的宽高样式(内联样式或CSS类均可),确保图表有渲染空间;
- 使用
useRef获取DOM元素,替代document.getElementById,更符合React组件生命周期规范; - 添加清理函数,在组件卸载时销毁ECharts实例,防止内存泄漏;
- 增加DOM元素存在性判断,避免初始化阶段找不到元素的报错。
内容的提问来源于stack exchange,提问作者Kamal Palei
相关产品推荐
相关产品推荐

