2017-01-23 13 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을"콜백 구현 만든이 작업을 수행하려면

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>" 
}   

문제는 내가 접근 할 수 있다는 것입니다 "이"에서 반작용도 I legendFormatter 함수의 변수에 액세스 할 수

하면 F() 정의되지

X가 정의되지

어떻게 컨텍스트를 onClick 함수에 바인딩 할 수 있습니까?

답변

0

당신은 생성자를 추가하고 결합 할 수 thislegendFormatter에 :

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

또는 대신 속성 초기화 화살표 기능으로 legendFormatter 기능을 만들 수 :

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

안녕 같은 JSX 접근 방법을 시도 할 수 있습니다 xf()에 액세스합니다. legendFormatter에서 'this'에 액세스하지 않는 문제입니다. 그것은 onclick 콜백에서 'this'와 변수에 액세스하고 있습니다. –

0

당신이 필요 this에 액세스하려면 범례 서식 함수 바인딩

화살표 기능을 사용할 수 있습니다.

legendFormatter = (data) => { 

것을 또한 당신이

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'에 액세스하지 않는 문제입니다. 그것은 onclick 콜백에서 'this'와 변수에 액세스하고 있습니다. legendFormatter 함수에서 JSX 객체를 반환하면 아마 dygraphs 렌더링 코드로 인해 "[object Object]"로 렌더링됩니다. –