简体   繁体   中英

Access Child Element's DOM Node in React

I am working with React & SVG.

In order to centre the viewbox on the child <g> , I need to get the 'BBox' value by calling the getBBox() API function on the child <g> element. My code looks like this:

// <SVG> Element
const SVGParent = React.createClass({
    componentDidMount : function(){
    let eleBBox = ReactDOM.findDOMNode( this.refs.gEle ).getBBox();
...

// Child <g> Element
const TemplateParent = React.createClass({
   render : function(){
      return(
         <g ref = "gEle">
...

The above line let eleBBox = ReactDOM.findDOMNOde( this.refs.gEle ) returns error: TypeError: _reactDom2.default.findDOMNode(...) is null

And indeed, the this.refs inside 'SVG' element is empty obj. How do I access the child <g> element, so I can access its DOM node?

Thanks,

You can chain refs to reach further down a component hierarchy if need be:

// Parent Element
componentDidMount: function() {
  let eleBBox = this.refs.templateRef.refs.gEle;
}

// Adding a ref to your child component
<TemplateParent ref='templateRef' ... />

But this can get a little unwieldy and isn't usually suggested. Refs should typically be treated as private to their component, since accessing them in this way weirdly makes the parent dependent on the naming schemes of its child.

A more common alternative is to expose a function on the child component:

const Parent = React.createClass({
  componentDidMount: function() {
    let eleBBox = this.refs.svgRef.getG();
  }

  render: function() {
    return(
      <Child ref='svgRef' />
    );
  }
}

const Child = React.createClass({
  getG: function() {
    return this.refs.gEle;
  }

  render: function() {
    return(
      <svg ...>
        <g ref='gEle' ...>
          <circle .../>
          <circle .../>
        </g>
      </svg>
    );
  }
}

Here's a working DEMO so you can check it out + DOCS for reference.

If you put a ref on a child you can get it in the parent like so, no need to look for the DOM node:

const SVGParent = React.createClass({
    componentDidMount : function(){
    let eleBBox = this.refs.gEle
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM