在 d3js 事件上执行 React js 函数

Execute a React js function on d3js event

我是 React 新手。我需要在单击 d3js 组件时调用 react js 函数。

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

handleClick: function(data){
    this.props.onClick(data);
},

点击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
   })

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

this.handleClick is not a function

怎么了?

当在匿名函数中引用时,this 不引用您的 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) )

另一种方法是将 "this" 绑定到外部变量,然后在其他函数中使用该变量。通常,人们将此变量称为 "self" 或 "that"。

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
} )

有关此及其工作原理的更多信息, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

如果您正在使用 ES6,只需使用箭头函数,箭头函数不会生成词法包装器,这在将 D3 与 React 结合使用时会导致此问题,因此只需执行以下操作:

const g = svg.selectAll(".arc")
  .data(pie(data))
  .enter().append("g")
  .on("mouseover", mouseover)
  .on("mouseout", mouseout)
  .on("click", d => {
     this.handleClick(); // my react method
})