我试图将事件侦听器添加到React组件中的SVG路径。我遵循了之前使用匿名函数的Stack Overflow回答(How to access SVG elements with Javascript),并且运行正常。当我尝试将回调设置为React组件类中定义的函数时,就像在此Stack Overflow应答(ReactJS - Add custom event listener to component)中一样,该函数未被调用。有趣的是,如果我在componentWillMount中引用函数并使用引用,它就可以工作。
import React, { Component } from "react";
export default class ProcessMap extends Component {
constructor(props) {
super(props);
this.hover = this.hover.bind(this);
}
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
svg.addEventListener("load", function() {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
//path1.addEventListener("click", this.hover, false); // this did not work
path1.addEventListener("click", t, false); // this works
});
}
hover() {
console.log("hover");
}
render() {
return (
<div>
<object id="drawing-svg" width="300" height="400" type="image/svg+xml" data="images/drawing.svg"></object>
</div>
);
}
};
答案 0 :(得分:1)
由于您尝试在新的常规this
中使用function()
,因此this
不再是React组件,因此无效。
替换
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
svg.addEventListener("load", function() {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
//path1.addEventListener("click", this.hover, false); // this did not work
path1.addEventListener("click", t, false); // this works
});
}
带箭头功能
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
svg.addEventListener("load", () => {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
path1.addEventListener("click", this.hover, false);
});
}
如果您不能使用ES6,那么您可以通过将其存储在变量中来跟踪this
:
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
var that = this;
svg.addEventListener("load", function() {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
path1.addEventListener("click", that.hover, false);
});
}
或使用.bind():
componentDidMount(){
const t = this.hover;
let svg = document.getElementById("drawing-svg");
svg.addEventListener("load", (function() {
let svgDoc = svg.contentDocument;
let path1 = svgDoc.getElementById("path3372");
path1.addEventListener("click", this.hover, false);
}).bind(this));
}