2017-01-23 79 views
1

我有一個使用Dygraphs呈現圖表的React組件。當我點擊它的標籤時,我想隱藏該系列。如何從回調中的React組件訪問「this」

createGraph() { 
    this.g = new Dygraph(
     this.refs.graphdiv, 
     this.state.options.data, 
     { 
     strokeWidth: 1, 
     labels: this.state.options.labels, 
     drawPoints:true, 
     stepPlot: true, 
     xlabel: 'Time', 
     ylabel: 'Metric value', 
     legend: 'always', 
     connectSeparatedPoints: true, 
     series: this.state.options.series, 
     labelsDiv: "labels", 
     legendFormatter: this.legendFormatter 
     } 
); 
} 

render() { 
return (
    <div> 
    <h2>Time series for system {this.props.sysId.replace(/_/g, ':')}</h2> 
    <h3>{this.props.date}</h3> 
    <div id="graphdiv" ref="graphdiv" style={{width: window.innerWidth - 50, height: window.innerHeight - 200}}></div> 
    <p></p> 
    <div id="labels"></div> 
    </div> 
); 
} 

要做到這一點,我已經實現了dygraphs回調「legendFormatter」,並創建了一個帶有的onClick回調標籤:

legendFormatter(data) { 
    if (data.x == null) { 
     // This happens when there's no selection and {legend: 'always'} is set. 

     let f =() => { 
      data.dygraph.setVisibility(0, false); 
      data.dygraph.updateOptions({}) 
     } 

     // return '<br>' + data.series.map((series) => { 
     // return series.dashHTML + ' ' + "<label onclick='f();'>" + series.labelHTML + "</label>" 
     // }, this).join('<br>'); 

     let x = data.dygraph; 

     return '<br>' + data.series[0].dashHTML + ' ' + "<label onclick='console.log(x);'>" + data.series[0].labelHTML + "</label>" 
}   

的問題是,我不能訪問「這個」來自陣營也不是我可以在legendFormatter功能訪問的變量:

f()是未定義

x是未定義

如何將上下文綁定到onClick函數?

回答

0

您可以添加一個構造函數和約束thislegendFormatter

constructor() { 
    super(); 
    this.legendFormatter = this.legendFormatter.bind(this); 
} 

或者你可以讓你的legendFormatter功能到屬性初始化箭頭函數:

legendFormatter = (data) => { 
    // ... 
}; 
+0

喜的JSX方法。它不是從legendFormatter訪問「this」的問題。它正在訪問'this'和來自onclick回調的變量。 –

0

要訪問this您需要綁定legendFormatter功能

您可以使用箭頭功能這

legendFormatter = (data) => { 

還訪問f()x你可以嘗試像

legendFormatter = (data) => { 
    if (data.x == null) { 
     // This happens when there's no selection and {legend: 'always'} is set. 

     let f =() => { 
      data.dygraph.setVisibility(0, false); 
      data.dygraph.updateOptions({}) 
     } 

     return <br>{data.series.map((series) => { 
         return {series.dashHTML}<label onClick={f()}>{series.labelHTML}</label><br> 
         }, this); 
       } 

     let x = data.dygraph; 

     return <br>{ data.series[0].dashHTML}<label onClick={()=>console.log(x);}>{data.series[0].labelHTML}</label> 
} 
+0

嗨。它不是從legendFormatter訪問「this」的問題。它正在訪問'this'和來自onclick回調的變量。如果我在legendFormatter函數中返回一個JSX對象,它會呈現爲「[object Object]」,可能是因爲dygraphs呈現代碼。 –

相關問題