【问题标题】:Why are some react-chartjs-2 options being ignored?为什么某些 react-chartjs-2 选项被忽略?
【发布时间】:2021-04-22 21:58:16
【问题描述】:

我有一个简单的折线图,我试图将网格线从默认的灰色更改,但是选项对象似乎有选择地工作。也许我错过了一些基本的东西,但我已经摆弄了几个小时并且无法让它工作,感谢任何帮助!我正在使用“react-chartjs-2”。

下面是我的 render() 方法,用于传递数据和选项。

render() {
        const data = {
            labels: this.state.realTimes,
            datasets: [
                {
                    label: "Price",
                    data: this.state.Prices,
                    fill: false,
                    backgroundColor: "rgb(255, 255, 255)",
                    borderColor: "rgba(255, 255, 255)"
                }
            ]
        };

        const options = {
            scales: {
                yAxis: {
                    beginAtZero: true, //this works

                    gridLines: {
                        color: "rgba(171,171,171,1)", //this doesn't
                        lineWidth: 0.5
                      }
                }
            }
        };
        return (
            <div>
                {this.state.loading ? (
                    this.loading()
                ) : (
                    <Line  data={data} options={options} width={600} height={160}  />
                )}
            </div>
        );
    }

【问题讨论】:

    标签: reactjs chart.js react-chartjs-2


    【解决方案1】:

    scales.yAxis.gridLines 更改为 scales.yAxis.grid 即可。

    请参阅 Chart.js 文档中的 Grid Line ConfigurationGrid Configuration 示例页面。

    请查看下面可运行的 JavaScript 代码,看看它是如何工作的。

    请看一下

    new Chart('line-chart', {
      type: 'line',
      data: {
        labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        datasets: [{
          label: 'My Dataset',
          data: [65, 59, 80, 81, 56, 55, 40],
          fill: false,
          borderColor: 'rgb(75, 192, 192)',
          tension: 0.2
        }]
      },
      options: {
        scales: {
          yAxis: {
            beginAtZero: true,
            grid: {
              color: 'rgb(0 ,0 ,255)',
              lineWidth: 0.5
            }
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/chart.min.js"></script>
    <canvas id="line-chart" height="100"></canvas>

    【讨论】:

      【解决方案2】:

      React chart.js 不是最新的 chart.js,所以你不能使用 v3。请使用 v2 语法,因为这是 react-chartjs 使用的。

      https://www.chartjs.org/docs/2.9.4/axes/styling.html#grid-line-configuration

      如果您将yAxes: {gridLines: {color: 'red'}} 更改为yAxes: [{gridLines: { color: 'red'}}],它应该可以正常工作

      【讨论】:

        猜你喜欢
        • 2014-12-27
        • 1970-01-01
        • 2021-01-08
        • 2022-06-15
        • 1970-01-01
        • 2021-10-28
        • 2021-11-06
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多