【问题标题】:Chart js :Adding onclick event on slice of doughnut chart is not working in react-chartjs-2图表 js:在圆环图切片上添加 onclick 事件在 react-chartjs-2 中不起作用
【发布时间】:2020-11-05 17:30:31
【问题描述】:

我试图在一片甜甜圈上添加 onclick 功能,它对 console.log 工作正常,但如果调用检查函数则不起作用。它给出的检查是未定义的。

class DoughnutChart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  check = (x, b) => {
    console.log("test check");
  };
  render() {
    return (
      <div>
        <Doughnut
          data={data}
          height={1}
          width={1}
          options={{
            responsive: true,
            maintainAspectRatio: true,
            cutoutPercentage: 85,
            tooltips: false,
            onClick: function (evt, item) {
              check("source", data.datasets[0].data[item[0]._index]);
              console.log("test");
            },
          }}
        />
      </div>
    );
  }
}
export default DoughnutChart;

【问题讨论】:

    标签: javascript reactjs user-interface chart.js chart.js2


    【解决方案1】:

    您在函数中无权访问“this”,因此您可以绑定 this 或使用如下箭头函数

          onClick: (evt, item) =>{
              this.check("source", this.state.data.datasets[0].data[item[0]._index]);
              console.log("test");
            },
    

    您还必须调用 this.check 并使用 this.state.data

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 2022-10-18
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多