繁体   English   中英

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

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

我正在使用React和SVG。

为了将视图框置于子<g> ,我需要通过调用子<g>元素上的getBBox() API函数来获取'BBox'值。 我的代码看起来像这样:

// <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">
...

上面的行let eleBBox = ReactDOM.findDOMNOde( this.refs.gEle )返回错误: TypeError: _reactDom2.default.findDOMNode(...) is null

实际上,'SVG'元素中的this.refs是空的obj。 如何访问子<g>元素,以便可以访问其DOM节点?

谢谢,

如果需要,您可以链接引用以进一步向下到达组件层次结构:

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

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

但这可能会有点笨拙,通常不建议。 Refs通常应被视为对其组件的私有,因为以这种方式访问​​它们会奇怪地使父级依赖于其子级的命名方案。

更常见的替代方法是在子组件上公开一个函数:

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>
    );
  }
}

这是一个有效的DEMO,所以你可以查看它+ DOCS以供参考。

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