2016-06-10 3 views
3

저는 React & SVG로 작업하고 있습니다.자식 요소의 DOM 노드에 액세스하십시오.

<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

그리고 실제로, this.refs 내부 'SVG'요소가 비어 obj가있다. DOM 노드에 액세스 할 수 있도록 자식 <g> 요소에 어떻게 액세스합니까?

감사합니다,

답변

1

당신이 아이에 심판을 두는 경우에 당신이 그렇게 같은 부모에서 그것을 얻을 수 있으며, DOM 노드를 찾을 필요가 :

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

당신은 체인 심판이 도달하지 할 수 있습니다

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

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

그러나이 방법은 약간 다루기 힘들고 일반적으로 권장되지 않습니다. 참조는 일반적으로 해당 구성 요소의 비공개로 처리해야합니다. 이러한 방식으로 액세스하면 부모가 자식의 명명 체계에 종속되게됩니다.

보다 일반적인 대안은 하위 구성 요소에 함수를 노출하는 것입니다

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 그것을 밖으로 + 확인할 수 있습니다 작업.

+0

Brad에게 감사드립니다. 나는 아이에게 기능을 노출시키는 두 번째 옵션을 채택했습니다. – Kayote

관련 문제