简体   繁体   中英

React google-charts callback

I want to create an event handler for Chart component from react-google-charts

Off. documentation has an example.

<Chart
    chartType="ScatterChart"
    rows={this.state.rows}
    columns={this.state.columns}
    options={this.state.options}
    graph_id="ScatterChart"
    width="100%"
    height="400px"
    chartEvents={this.chartEvents} // <- this is event handler
   />

chartEvents looks like

this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

How can I refer to class context from the callback function? I want to change my local state.

this.chartEvents=[
  {
    eventName : 'select',
    callback  : function(Chart) {
        // here I want to refer to this.setState
        console.log("Selected ",Chart.chart.getSelection());
    }
  }
];

I had the same need as you and was able to do it. You can create a variable (superClass in the example below) and assign the value of the class (this) to it. This way you can still access it inside the scope of the callback.

const superClass = this;
this.chartEvents = [
  {
    eventName: 'select',
    callback(Chart) {
        // here you can refer to superClass.setState
        console.log("Selected ",Chart.chart.getSelection());
    },
  },
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM