1. 程式人生 > 實用技巧 >react專案匯入@antv/g2的TypeError: Cannot read property 'appendChild' of null問題解決

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已經渲染完了