javascript - 反应回调点击事件`this`未定义
问题描述
我正在使用 d3 并做出反应以创建图表。单击按钮将更新图表。在图表的组件中是一个 onclick 事件侦听器,但是“this”不断混淆
一种带有箭头函数的方法返回Uncaught TypeError: node.getAttribute is not a function
:
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
引用了组件实例。所以我研究了如何引用点击事件,发现使用e
orevent.target
应该可以解决问题。然而,在反应中,返回一个错误:Uncaught TypeError: Cannot read property 'target' of undefined
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.setupButtons
和都this.toggleDisplay()
定义在同一个方法中,属于一个组件。
编辑:这个问题似乎不是所提供问题的“重复”。显然,这是 D3 处理的问题event
,而不是使用的问题this
。此问题的解决方案(添加d3.event.target
而不是event.target
)未作为此假定重复的问题的答案提供。
解决方案
您可以将外部 this 的引用存储到另一个变量中。我通常将它存储到一个变量var that = this
中,然后您可以that
在需要的地方引用该变量。
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)
});
}
推荐阅读
- module - Magento 2.3.4 Setup_Module
- excel - 如何在保留单元格信息的同时将 Excel 文件转换为 CSV?
- regex - 正则表达式允许单词之间有空格(没有特殊字符)但在开头删除空格
- android - 如何从带有动画的容器中删除片段?
- uwp - H264解码性能不佳
- scala - 在 Spark scala 中更新数据框的最佳方法
- r - 您如何制作搜索栏来查询闪亮仪表板中的格式化表
- mysql - 在基本 Spring-MVC(非引导)项目中访问 @Autowired 存储库(JPA)的问题
- mysql - Mysql:选择但仅在有两个条件的行时才计数
- shell - 如何将变量从 AppleScript 传递到 shell 命令?