[英]Execute a React js function on d3js event
我是新来的。 单击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
怎么了?
在匿名函数中引用时,它不引用您的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”绑定到外部变量,然后在其他函数中使用该变量。 人们通常将这个变量称为“自我”或“那个”。
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
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.