【发布时间】:2017-11-22 18:24:12
【问题描述】:
我正在尝试将事件侦听器添加到 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>
);
}
};
【问题讨论】:
-
thisinsidecomponentDidMount与this在事件调用的函数内不同。
标签: javascript reactjs svg addeventlistener