Snap.svg in React - how to access the svg in a lifecycle method?

梦想与她 提交于 2019-12-06 11:06:09

You are doing a direct DOM manipulation with Snap.svg and neither render nor componentWillReceiveProps is a good place to do that. I recommend you to do that in componentDidUpdate which calls immediately after component gets rendered. But this will not be invoked for the initial render. So we have to do this DOM manipulation in both componentDidUpdate and componentDidMount. To prevent repeating the same code, you can keep this operation in another common class method and call it from both componentDidUpdate and componentDidMount. Also, since your props have been updated at this point you can simply access them with this.props inside the new class method.

Example:

// @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} />
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!