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

我浏览了React Refs 的 React 文档,这就是它所说的内容createRef()

createRef() 接收底层 DOM 元素作为其当前属性。当 ref 属性用于自定义类组件时, ref 对象接收组件的已安装实例作为其 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 Refimg作为属性传递给React 元素ref

React Ref 在这里做什么?

img最终将成为一个对象,该对象具有名为 ref 的属性,其值为 value this.imageRef,它如何接收img当前属性?

如果是这样的话this.imageRef.current = img(object),那是有可能的。但我不明白上面的方式即ref={this.imageRef}

另外,对于这两个控制台语句,这是我得到的输出。


https://img1.sycdn.imooc.com/65a885210001091a04280165.jpg

因此,在构造函数中,当前属性是null有效的。但是,当我展开它时,它具有ieimg中打印的所有属性,如何componentDidMountclinetHeght

我不知道,是否对此有简短的解释,或者有人必须纠正整页。如果这个问题太大而无法回答,外部链接或参考资料会有所帮助。

我对库实现的细节也不感兴趣,只是一个概述就会有所帮助,这样我就可以React.createRef()放心地或毫无疑问地使用。


翻阅古今
浏览 38回答 2
2回答

慕丝7291255

对于如何ref分配,您必须记住 JSX 编译为普通的旧 JavaScript。幕后发生的事情的一个非常简单的例子如下:function createRef(initialValue) {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; current: initialValue&nbsp; &nbsp; }}const root = document.getElementById('root');function render(elementType, innerText, ref) {&nbsp; &nbsp; const el = document.createElement(elementType);&nbsp; &nbsp; if (ref) {&nbsp; &nbsp; &nbsp; &nbsp; ref.current = el;&nbsp; &nbsp; }&nbsp; &nbsp; el.innerText = innerText;&nbsp; &nbsp; root.replaceChildren(el);}const ref = createRef(null);console.log(ref);render('div', 'Hello World', ref);console.log(ref);&nbsp; &nbsp;&nbsp;<div id="root"></div>所以基本上 - 当您使用 时<img ref={this.imageRef} src={urls.regular} alt={description} />, 会ref作为属性传递,并且在呈现它的函数中,它将实际的 DOM 节点分配给ref.current。

繁花如伊

因此,为了回答你的第一个问题,React 会将 DOM 元素分配给currentref 的属性。在您的情况下,这意味着this.imageRef.current组件渲染后它将成为对图像元素的引用。控制台输出部分让它有点令人困惑,但这并不是由于 React 所做的一些魔法,而是由于浏览器控制台如何处理在记录对象后属性发生变化的对象。例如,如果您在控制台中运行以下代码,然后展开输出,您将看到与 ref 中看到的相同行为。const obj = { current: null }console.log(obj)obj.current = 'something'这是它的样子的屏幕截图。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript