我有一个使用Dygraphs渲染图表的React组件。我想在点击它的标签时隐藏这个系列。
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回调&#34; legendFormatter&#34;并使用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>"
}
问题是我无法访问&#34;这个&#34;来自React,我也可以访问legendFormatter函数中的变量:
f()未定义
x未定义
如何将上下文绑定到onClick函数?
答案 0 :(得分:0)
您可以添加构造函数并将this
绑定到legendFormatter
:
constructor() {
super();
this.legendFormatter = this.legendFormatter.bind(this);
}
或者您可以将legendFormatter
函数改为属性初始化箭头函数:
legendFormatter = (data) => {
// ...
};
答案 1 :(得分: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>
}