反应回调点击事件`this`未定义

时间:2019-08-13 03:25:18

标签: javascript reactjs this arrow-functions

我正在使用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引用了组件实例。因此,我研究了如何引用click事件,发现应该使用eevent.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.setupButtonsthis.toggleDisplay()都是用同一方法定义的,属于组件。

编辑:该问题似乎与所提供问题没有“重复”。这显然是D3处理event而不是使用this的问题。该问题的解答(用d3.event.target代替event.target代替)未提供作为该问题的答案。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

d3的处理方式略有不同。可从d3本身(d3.event)访问该事件。

来源:https://octoperf.com/blog/2018/04/17/d3-js-mouse-events-and-transitions-tutorial/#how-to-use-d3-event-object

答案 2 :(得分:-1)

在外部函数中分配var that = this。现在,您可以引用外部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)
        });
}