首页 > 解决方案 > 反应传递参考到相邻组件

问题描述

我想访问一个 SVG 元素的位置,以在 React 中绘制另一个 SVG 元素。因此,我想使用getBoundingClientRect()并且需要从相邻的 SVG 元素访问第一个 SVG 元素的 DOM。

编辑: 示例:我有一个circle并且想rect在它上面画一个。

我可以在安装后访问圆圈参考OtherSVGELement。但是在渲染时我无法访问相邻circle元素 refrect

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.firstRef = React.createRef();
    };
    render() {
        return (
            <svg>
                <circle ref={this.firstRef} />
                <OtherSVGElement circleRef={this.firstRef}/>
            </svg>
        )
    };
};

class OtherSVGElement extends React.Component {
    constructor(props) {
        super(props);
    };

    componentDidMount() {
        console.log(this.props.circleRef.current);
    };


    render() {
       return (
           <svg>
               /* Doesn't work; current is null */
               <rect x=this.props.circleRef.current.x /> 
           </svg>
       )
    };
};

我该如何克服这个问题?在我的情况下,圆圈位置更难获得。这就是为什么我想使用getBoundingClientRect().

标签: javascriptreactjsref

解决方案


你的直觉是正确的。您将能够在其他生命周期挂钩中访问 ref,例如componentDidMountand componentDidUpdate

componentDidMount() {
  console.log(this.props.otherRef);
}

顺便说一句,您可能正在寻找currentref ( this.props.otherRef.current) 上的属性,这将是对 DOM 节点的引用。


推荐阅读