dwi*_*ank 3 svg reactjs snap.svg
我有一个 svg 地图组件,我想在道具更改时更新它。在某些路径上添加和减去类……诸如此类。
Snap.svg 似乎是要走的路。如果有人知道更好的方法,我想听听!
所以这是我的渲染方法,用皱眉标记的两行是我想要在生命周期方法中工作的那些,例如 ComponentWillReceiveProps
render() {
var map = Snap('#map');
Snap.load("images/map.svg", function(data){
if (map) {
map.append(data);
const a2047 = map.select('#a2047'); <---- :(
a2047.attr({stroke:'yellow', strokeWidth:'6px'}) <---- :(
}
})
return (
<div className="map" id="map"/>
);
}
Run Code Online (Sandbox Code Playgroud)
问题是,map除了在这个Snap.load回调中之外,在其他任何地方都无法工作。我尝试了几种方法,使用state, window.map, this.map... 并且我收到诸如“select is not a function”之类的错误。
如何访问 中的地图ComponentWillReceiveProps?
或者 Snap.svg 甚至是这个应用程序的方法?
您正在使用 Snap.svg 进行直接的 DOM 操作,这既不是一个好地方,render也不componentWillReceiveProps是这样做的好地方。我建议您componentDidUpdate在组件呈现后立即调用。但这不会为初始渲染调用。所以我们必须在componentDidUpdate和中都做这个 DOM 操作componentDidMount。为了防止重复相同的代码,你可以保持此操作另一种常见的类的方法和来自调用它componentDidUpdate和componentDidMount。此外,由于此时您的道具已更新,您可以简单地this.props在新的类方法中访问它们。
// @sigfried added to answer his comment below
import Snap from 'snapsvg-cjs';
export default class Mermaid extends Component {
svgRender() {
let element = Snap(this.svgDiv)
Snap.load("images/map.svg", function(data){
if (element) {
element.append(data);
}
});
}
componentDidMount() {
this.svgRender();
}
componentDidUpdate() {
this.svgRender();
}
render() {
return <div ref={d=>this.svgDiv=d} />
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4830 次 |
| 最近记录: |