[英]React pass ref to adjacent component
我想訪問一個SVG元素的位置,以在React中繪制另一個SVG元素。 因此,我想使用getBoundingClientRect()
並需要從相鄰的SVG元素訪問第一個SVG元素的DOM。
編輯:例子:我有一個circle
,想在它上面畫一個rect
。
在OtherSVGELement
安裝后,我可以訪問圈子參考。 但是渲染rect
時我無法訪問相鄰的circle
元素ref
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()
。
你的直覺是正確的。 您將能夠在其他生命周期掛鈎中訪問ref,例如componentDidMount
和componentDidUpdate
:
componentDidMount() {
console.log(this.props.otherRef);
}
順便說一句,您可能正在查找ref上的current
屬性( this.props.otherRef.current
),它將作為對DOM節點的引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.