gpt4 book ai didi

javascript - React.createRef() 实际上是如何工作的?

转载 作者:行者123 更新时间:2023-12-03 15:53:51 28 4
gpt4 key购买 nike

我经历了React docs for React Refs ,这就是它所说的createRef()

createRef() receives the underlying DOM element as its current property. When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current .


我对此有一些疑问。首先看看下面的组件。
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()方法,我将 React Ref 传递给 img将元素作为属性作为 ref .
React Ref 在这里做了什么? img最终将成为一个对象,该对象具有名为 ref 的属性,其值为 this.imageRef , 如何接收 img因为它是当前的属性(property)?
如果是这样的 this.imageRef.current = img(object) , 有可能。但我不明白上述方式,即 ref={this.imageRef}此外,对于这两个控制台语句,这是我得到的输出。
enter image description here
因此,在构造函数中,当前属性是 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 id="root"></div>

所以基本上 - 当你使用 <img ref={this.imageRef} src={urls.regular} alt={description} /> , ref作为属性传递,在渲染它的函数中,它将实际的 DOM 节点分配给 ref.current .

关于javascript - React.createRef() 实际上是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65418747/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com