2016-11-09 24 views
2

我想爲圖表組件創建一個事件處理程序react-google-charts反應谷歌圖表回調

關閉。文檔有一個例子。

<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看起來像

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

我如何引用類的上下文從回調函數?我想改變我的本地狀態。

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

如果您嘗試在回調中設置狀態,會出現什麼錯誤? –

回答

0

我和你有同樣的需求,並能夠做到這一點。 您可以創建一個變量(以下示例中爲superClass),併爲其分配類的值(this)。這樣你仍然可以在回調的範圍內訪問它。

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