我想访问一个 SVG 元素的位置,以便在 React 中绘制另一个 SVG 元素。因此,我想使用 getBoundingClientRect() 并需要从相邻的 SVG 元素访问第一个 SVG 元素的 DOM。
编辑:
示例:我有一个圆
,想在其顶部绘制一个矩形
。
在 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()
。
最佳答案
你的直觉是正确的。您将能够访问其他生命周期 Hook 中的引用,例如 componentDidMount
和 componentDidUpdate
:
componentDidMount() {
console.log(this.props.otherRef);
}
顺便说一句,您可能正在寻找 ref 上的 current
属性 (this.props.otherRef.current
),它将是对DOM 节点。
关于javascript - React 将 ref 传递给相邻组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57469680/