React refs 是如何使用的,何时使用? [英] React refs how are they used, and when are they used?

查看:48
本文介绍了React refs 是如何使用的,何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,感谢您阅读这个问题!

我已经学习 React 几个星期了,我在尝试理解 refs 如何获取 React 的实例并将其放入 JS 变量时遇到了困难.

例如,我们可以讨论文档的示例:

class CustomTextInput 扩展 React.Component {构造函数(道具){超级(道具);this.focusTextInput = this.focusTextInput.bind(this);}焦点文本输入(){//使用原始 DOM API 显式聚焦文本输入this.textInput.focus();}使成为() {//使用 `ref` 回调来存储对文本输入 DOM 的引用//实例字段中的元素(例如,this.textInput).返回 (<div><输入类型=文本"ref={(输入)=>{ this.textInput = 输入;}}/><输入类型=按钮"value="关注文本输入"onClick={this.focusTextInput}/>

);}}

我知道 ref 获取将要呈现的输入元素,并使用 this.textInput 将其存储到类字段中.

但是我不明白为什么传递给 refs 的参数是(输入)如果嵌套了 jsx 标签会发生什么?例如两个输入?

还有没有明确的方法来引用使用 React 渲染/返回创建的元素?我说的是面向对象编程之类的东西:className.instanceName 或从 HTML 元素创建实例:new elementName().

感谢您的帮助!

解决方案

React 支持可以附加到任何组件的特殊属性.ref 属性带有回调函数,callback 会在组件挂载或卸载后立即执行.

写作时

<输入类型=文本"ref={(输入)=>{ this.textInput = 输入;}}/>

React 提取 ref 属性并在组件挂载后调用回调.在该回调函数中,react 传递输入的实例,这是您在此处作为参数获得的.把上面看成一个函数

<输入类型=文本"ref={this.callback}/>

那个回调看起来像

const callback = (input) =>{this.textInput = 输入;}

根据文档:

<块引用>

当 ref 属性用于 HTML 元素时,ref 回调接收底层 DOM 元素作为其参数.

关于您的下一个问题:

<块引用>

但是我不明白为什么将参数传递给 refs是(输入)如果嵌套了 jsx 标签会发生什么

传递给 div 的参数在您的示例中只是作为输入引用,您可以随意调用它,例如 inputinputRefinstance

在多个jsx标签嵌套中,ref应用于传递ref属性的元素.例如

<div>Hello React</div>

ref 获取应用于外部 div 的实例,您可以从中访问子元素.

Codesandbox

<块引用>

也没有明确的方法来引用正在创建的元素使用 React 渲染/返回

Well refs 是 React 提供的一种引用方式,元素被创建.但是,您应该只在

时使用 refs
  • 管理焦点、文本选择或媒体播放.
  • 触发命令式动画.
  • 与第三方 DOM 库集成.

大多数情况下,props 是父组件与其子组件交互的唯一方式.要修改一个孩子,你可以用新的道具重新渲染它.例如,如果您希望更改元素上的类,而不是访问该元素并更改它的类,您可以将动态道具传递给它,而不是像

或者事实上,使用 state 进行必要的更新

Hello and thank you for reading this question!

I have been learning React for some weeks and I have difficulties trying to understand how refs can get React's instance and put it into a JS variable.

For example we could discuss the documentation's example:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in an instance field (for example, this.textInput).
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

I understand that the ref gets the input element which will be rendered and stores it into a class field using this.textInput.

However I do not understand why the parameter being passed to the refs is (input) what could happen if there were jsx tags nested? For example two inputs?

Also is there not a clear way to reference the elements being created with React render/return? I am talking about something like object oriented programming: className.instanceName or creating instance from the HTML elements with: new elementName().

Thank you for your help!

解决方案

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

When you write

<input
      type="text"
      ref={(input) => { this.textInput = input; }} />

React extracts the ref attribute and invokes a callback after the component is mounted. In that callback function react passes the instance of the input, which is what you get as the parameter here. Think of the above as a function

<input
      type="text"
      ref={this.callback} />

and that callback will look like

const callback = (input) => { 
   this.textInput = input; 
}

According to the docs:

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument.

Regarding your next question:

However I do not understand why the parameter being passed to the refs is (input) what could happen if there were jsx tags nested

The parameter being passed to div is just referenced as input in your example, you can call it anything you want, like input, inputRef, instance

In multiple jsx tags are nested, the ref is applied on the element on which ref attribute is passed. For instance

<div ref={this.getRef}>
   <div>Hello React</div>
</div>

The ref gets the instance of is applied to the outer div from which you can access the child elements.

Codesandbox

Also is there not a clear way to reference the elements being created with React render/return

Well refs is a way provided by React to reference, elements being created. However you should only use refs when

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Most often, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. For example if you wish to change the class on an element, instead of getting an access to the element and changing it class, you would pass the dynamic prop to it instead like

<div className={this.props.className} />

Or as a matter of fact, use state to make necessary updates

这篇关于React refs 是如何使用的,何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆