简体   繁体   English

在React中访问子元素的DOM节点

[英]Access Child Element's DOM Node in React

I am working with React & SVG. 我正在使用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. 为了将视图框置于子<g> ,我需要通过调用子<g>元素上的getBBox() API函数来获取'BBox'值。 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 上面的行let eleBBox = ReactDOM.findDOMNOde( this.refs.gEle )返回错误: TypeError: _reactDom2.default.findDOMNode(...) is null

And indeed, the this.refs inside 'SVG' element is empty obj. 实际上,'SVG'元素中的this.refs是空的obj。 How do I access the child <g> element, so I can access its DOM node? 如何访问子<g>元素,以便可以访问其DOM节点?

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. Refs通常应被视为对其组件的私有,因为以这种方式访问​​它们会奇怪地使父级依赖于其子级的命名方案。

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. 这是一个有效的DEMO,所以你可以查看它+ DOCS以供参考。

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: 如果你把一个引用放在一个孩子上,你可以像这样在父母那里得到它,不需要查找DOM节点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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