react項目導入@antv/g2的TypeError: Cannot read property 'appendChild' of null問題解決


這個問題起因是因為id為c11的div標簽不存在導致的,在g2畫圖之前,div並未渲染

 

 1 import React from 'react';
 2 import ReactDOM from 'react-dom';
 3 import './index.css';
 4 import { Chart } from '@antv/g2';
 5 
 6 ReactDOM.render(
 7   <React.StrictMode>
 8     <div id="c11"></div>
 9   </React.StrictMode>,
10   document.getElementById('root')
11 );
12 
13 const data = [
14     { year: '1951 年', sales: 38 },
15     { year: '1952 年', sales: 52 },
16     { year: '1956 年', sales: 61 },
17     { year: '1957 年', sales: 145 },
18     { year: '1958 年', sales: 48 },
19     { year: '1959 年', sales: 38 },
20     { year: '1960 年', sales: 38 },
21     { year: '1962 年', sales: 38 },
22 ];
23 const chart = new Chart({
24     container: 'c11',
25     autoFit: false,
26     width: 400,
27     height: 300,
28 });
29 
30 chart.data(data);
31 chart.scale('sales', {
32     ticks: [0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200],
33     formatter: (val) => `¥${val}`,
34 });
35 
36 chart.axis('sales', {
37     title: {},
38 });
39 
40 chart.interval().position('year*sales');
41 
42 chart.render();

把g2代碼寫在ReactDom后面就可以解決這個問題,這時候c11已經渲染完了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM