我有一個使用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函數?
喜的JSX方法。它不是從legendFormatter訪問「this」的問題。它正在訪問'this'和來自onclick回調的變量。 –