如何解决ReactJS无法使用ref回调获取对类组件的引用
我试图从父组件获取对子组件(类组件)的引用,我遇到两个问题:
Parent component
private childRef: RefObject<any> = React.createRef();
<Child ref={this.childRef} />
-
引用回调不会触发,并且在我的引用中得到空
{current: null}
。 -
React-dev-tools警告我从功能组件传递ref,但我的子组件是类组件。
react_devtools_backend.js:2273 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
任何人都可以帮忙吗?
仅供参考,将我的应用程序从PReact迁移到React时发生此问题。 在Preact中,裁判常用于正确传递:
父母
<Child ref={(ref: any) => {
if (ref && ref._component) {
this.childRef = ref._component._component
}
}}
</Child>
解决方法
您必须转发参考
const Child = React.forwardRef((props,ref) => (
<div ref={ref} >
....
</div>
))
引用不会自动从功能组件传递到其DOM元素。因此,您必须手动传递它。进一步了解https://reactjs.org/docs/forwarding-refs.html
,将其包装在div中。试试这个:
Parent component
private childRef: RefObject<any> = React.createRef();
<div ref={this.childRef} >
<Child />
<div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。