在d3js事件上执行React js函数

ntr*_*rax 1 d3.js reactjs

我是新来的。单击d3js组件时,我需要调用react js函数。

我在React组件中有一个d3js条形图。在同一组件中,我有以下方法:

handleClick: function(data){
    this.props.onClick(data);
},
Run Code Online (Sandbox Code Playgroud)

单击d3js时,我需要调用此函数:

var g = svg.selectAll(".arc")
    .data(pie(data))
    .enter().append("g")
    .on("mouseover", mouseover)
    .on("mouseout", mouseout)
    .on("click", function(d) {
    this.handleClick(); // my react method
   })
Run Code Online (Sandbox Code Playgroud)

但这不起作用。我在chrome中的输出是这样的:

this.handleClick is not a function
Run Code Online (Sandbox Code Playgroud)

怎么了?

Sil*_*rom 5

在匿名函数中引用时,它不引用您的react-component。实际上,这是指单击处理程序创建的上下文。

这是一个常见的JavaScript错误观念。在另一个函数中访问特定“ this”变量的一种常用方法是将该函数绑定到特定this对象。

var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", function(d) {
    this.handleClick(); // my react method
}.bind(this) )
Run Code Online (Sandbox Code Playgroud)

另一种选择是将“ this”绑定到外部变量,然后在其他函数中使用该变量。人们通常将这个变量称为“自我”或“那个”。

var that = this;
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", function(d) {
    that.handleClick(); // my react method
} )
Run Code Online (Sandbox Code Playgroud)

有关此功能及其工作方式的更多信息, https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this