如何从回调中的React组件访问“this”
问题描述:
我有一个使用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函数?
答
您可以添加一个构造函数和约束this
到legendFormatter
:
constructor() {
super();
this.legendFormatter = this.legendFormatter.bind(this);
}
或者你可以让你的legendFormatter
功能到属性初始化箭头函数:
legendFormatter = (data) => {
// ...
};
答
要访问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呈现代码。 –
喜的JSX方法。它不是从legendFormatter访问“this”的问题。它正在访问'this'和来自onclick回调的变量。 –