【发布时间】:2020-06-15 09:31:36
【问题描述】:
标题非常简单,我需要访问通过我的组件的子元素传递的子元素上的属性(准确地说是 ref),这意味着我无法在父 afaik 中传递 ref . 这是一个突出我的问题的最小示例:
import React from "react";
class Child extends React.Component {
myRef = React.createRef();
render() {
return <div ref={this.myRef}>child</div>;
}
}
const Parent = ({ children }) => {
const myChild = React.Children.toArray(children).find(
child => child.type === Child
);
// I want to access this
console.log(myChild.myRef);
// but it's undefined
return (
<div>
<h1>Parent</h1>
{children}
</div>
);
};
// I can't really change this component
export default function App() {
return (
<div className="App">
<Parent>
<Child />
</Parent>
</div>
);
}
我制作了一个代码框来突出我的问题https://codesandbox.io/s/eloquent-wing-e0ejh?file=/src/App.js
【问题讨论】:
-
您能详细说明一下您想要实现的目标吗?将 Refs 传递给父组件的机会并不是您真正需要的。
-
@jogesh_pi nope 因为不幸的是 Child 没有设置在 Parent 中
-
@YevgenGorbunkov 我需要在 Parent 中访问 Child 的 dom 元素,因为我需要检查它的高度/scrollPosition 并将其与 Parent 匹配
标签: javascript reactjs