javascript - 反应传递参考到相邻组件
问题描述
我想访问一个 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()
.
解决方案
你的直觉是正确的。您将能够在其他生命周期挂钩中访问 ref,例如componentDidMount
and componentDidUpdate
:
componentDidMount() {
console.log(this.props.otherRef);
}
顺便说一句,您可能正在寻找current
ref ( this.props.otherRef.current
) 上的属性,这将是对 DOM 节点的引用。
推荐阅读
- python - Python use curl with subprocess, write outpute into file
- hibernate - 仅需要实体 id 时如何避免初始化 Hibernate 代理
- c# - QueueBackgroundWorkItem 与 Task.Run 用于后台任务
- jquery - ajax POST 响应为空
- java - 编写 ExecutorService 以更新 AtomicBoolean 值的方法
- javascript - 变量跟踪用户尝试不更新
- java - 为什么无障碍服务无法采取用户行动?
- mysql - 如何使用 VB.NET 选择 mysql 中的所有列值
- sorting - 使用链表在动态堆栈中排序
- django - Filtering another model field count for each item from object_list (List View, Django)