"Cannot read property of undefined at am4themes..." 在 AmCharts4 中通过主题格式化 chart.plotContainer

"Cannot read property of undefined at am4themes..." while formatting chart.plotContainer via theme in AmCharts4

我想通过主题填充 XYChart 的绘图区域;但是我收到以下错误:Uncaught TypeError: Cannot read property 'background' of undefined at am4themes_myTheme

我在尝试给出答案时参考了 this documentation

这就是我想要的,但不是通过主题:page.html

var chart = am4core.create("viz", am4charts.XYChart);
chart.plotContainer.background.fill = am4core.color('green');

这是我为我的自定义主题所做的尝试: myTheme.js

function am4themes_bi(target) {
    if (target instanceof am4charts.Chart) {
        target.plotContainer.background.fill = am4core.color('green');
    }
}

如何更改我的主题功能,使其将绘图区域变为绿色?

根据错误信息,似乎 plotContainer 尚未定义。在尝试设置 target.plotContainer 之前,您需要先检查一下是否定义了它:

function am4themes_bi(target) {
    if (target instanceof am4charts.Chart) {
      if (target.plotContainer !== undefined) { 
        target.plotContainer.background.fill = am4core.color('green');
      }
    }
}

Codepen