首页 > 解决方案 > 反应回调点击事件`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引用了组件实例。所以我研究了如何引用点击事件,发现使用eorevent.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)未作为此假定重复的问题的答案提供。

标签: javascriptreactjsthisarrow-functions

解决方案


您可以将外部 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)
            });
        }

推荐阅读