Javascript 反应回调单击事件`this`未定义
我使用d3和react创建图表。单击按钮将更新图表。在图表的组件中有一个onclick事件监听器,但是“this”总是混淆在一起 一个带有箭头函数的方法返回未捕获的TypeError:node.getAttribute不是函数:Javascript 反应回调单击事件`this`未定义,javascript,reactjs,this,arrow-functions,Javascript,Reactjs,This,Arrow Functions,我使用d3和react创建图表。单击按钮将更新图表。在图表的组件中有一个onclick事件监听器,但是“this”总是混淆在一起 一个带有箭头函数的方法返回未捕获的TypeError:node.getAttribute不是函数: this.setupButtons= function() { d3.select('#toolbar') .selectAll('.buttons') .on('click', ()=> {
this.setupButtons= function() {
d3.select('#toolbar')
.selectAll('.buttons')
.on('click', ()=> {
d3.selectAll('.buttons').classed('active', false);
var button = d3.select(this);
button.classed('active', true);
var buttonId = button.attr('id');
this.toggleDisplay(buttonId)
});
}
*/
这当然是因为This
引用了组件实例。因此,我研究了如何引用click事件,发现使用e
或event.target
应该可以解决这个问题。但是,在react中,返回一个错误:uncaughttypeerror:无法读取未定义的属性“target”
this.setupButtons= function() {
d3.select('#toolbar')
.selectAll('.buttons')
.on('click', (e)=> {
d3.selectAll('.buttons').classed('active', false);
var button = d3.select(e.target);
button.classed('active', true);
var buttonId = button.attr('id');
this.toggleDisplay(buttonId)
});
}
this.setupbutton
和this.toggleDisplay()
都是在同一方法中定义的,属于组件
编辑:此问题似乎与提供的问题“重复”。这是D3处理
事件
的问题,显然不是使用此
。此问题的解决方案(添加d3.event.target
而不是event.target
)未作为问题的答案提供,这可能重复。在外部函数中分配var=this
。现在您有了一种方法来引用外部此
this.setupButtons = function () {
var that = this;
d3.select('#toolbar')
.selectAll('.buttons')
.on('click', function() {
d3.selectAll('.buttons').classed('active', false);
var button = d3.select(this);
button.classed('active', true);
var buttonId = button.attr('id');
that.toggleDisplay(buttonId)
});
}
您可以将外部变量的引用存储到另一个变量中。我通常将其存储到一个变量中,如
var=this
,然后您可以在需要时引用变量this
this.setupButtons= function() {
var that = this;
d3.select('#toolbar')
.selectAll('.buttons')
.on('click', ()=> {
d3.selectAll('.buttons').classed('active', false);
var button = d3.select(that);
button.classed('active', true);
var buttonId = button.attr('id');
that.toggleDisplay(buttonId)
});
}
d3
处理事情的方式有点不同。事件可从d3
本身访问(d3.event
)
来源:只需使用常规函数而不是箭头函数。jQuery无法向arrow函数提供thisArg,因为arrow函数没有自己的
this
。我需要参考var button=d3中的单击事件。选择(e.target)
然后我需要调用this.toggleDisplay(buttonId)
,这是另一个使用组件的this
e.target
的函数。我真的不明白为什么e
会有未定义的。不过我不知道反应如何。d3
处理事情的方式有点不同。事件可从d3
本身访问(d3.event
)。老实说,我不知道这在这种情况下如何转化为对您的帮助,但至少您不会调试正常的事件
@Ezra,您能将此作为正式答案吗?这似乎对我有用。非常感谢。虽然我不知道你说的“老实说”是什么意思,但我不知道在这种情况下这会如何转化为对你的帮助`