React.createRef()实际上是如何工作的?
我浏览了 React Refs 的 React 文档,这就是它所说的createRef()
createRef() 接收底层 DOM 元素作为其当前属性。当 ref 属性用于自定义类组件时, ref 对象接收组件的已安装实例作为其当前 .
我对此有一些疑问。首先看看下面的组件。
import React, { Component } from "react";
class ImageCard extends Component {
constructor(props) {
super(props);
this.imageRef = React.createRef();
console.log("Called in constructor", this.imageRef);
}
componentDidMount() {
console.log("Called when component did mount ", this.imageRef);
}
render() {
const { description, urls } = this.props.image;
return (
<div>
<img ref={this.imageRef} src={urls.regular} alt={description} />
</div>
);
}
}
export default ImageCard;
因此,在构造函数中,我创建了一个React Ref,并分配给了一个名为imageRef. 并且,在render()方法中,我通过了 阵营价到img阵营元件作为作为一个属性ref。
React Ref 在这里做什么?
img最终会成为一个对象,它有一个名为 ref 的属性this.imageRef,它的值是如何接收img的?
如果它是这样的this.imageRef.current = img(object),它可能是。但我不明白上述方式即ref={this.imageRef}
此外,对于这两个控制台语句,这是我得到的输出。
因此,在构造函数中当前属性null是有效的。但是,当我展开它时,它具有img打印的所有属性,componentDidMount即clinetHeght 如何?
我不知道,如果对此有简短的解释,或者有人必须纠正整页。如果这太大而无法回答,外部链接或参考资料会有所帮助。
我也对库实现的细节不感兴趣,只是概述会有所帮助,这样我就可以React.createRef()放心或毫无疑问地使用。
回答
对于如何ref分配,您必须记住 JSX 编译成普通的旧 javascript。关于幕后发生的事情的一个非常简单的例子是这样的:
function createRef(initialValue) {
return {
current: initialValue
}
}
const root = document.getElementById('root');
function render(elementType, innerText, ref) {
const el = document.createElement(elementType);
if (ref) {
ref.current = el;
}
el.innerText = innerText;
root.replaceChildren(el);
}
const ref = createRef(null);
console.log(ref);
render('div', 'Hello World', ref);
console.log(ref);
<div></div>
所以基本上 - 当您使用 时<img ref={this.imageRef} src={urls.regular} alt={description} />, 将ref作为属性传递,并且在呈现它的函数中,它将实际的 DOM 节点分配给ref.current.