Home  >  Article  >  Web Front-end  >  What are refs in react

What are refs in react

王林
王林Original
2020-11-25 10:21:062759browse

refs in react is a special attribute supported by react. This special attribute allows us to refer to the corresponding support instance returned by render(). This way we can ensure we always get the correct instance at any time.

What are refs in react

The operating environment of this tutorial: windows10 system, react16 version. This method is suitable for all brands of computers.

(Learning video sharing: react tutorial)

Attribute introduction:

React supports a very special attribute Ref, which you can use to bind Targeted to any component output by render().

This special property allows you to reference the corresponding backing instance returned by render(). This ensures that you always get the correct instance at any time.

Usage:

Bind a ref attribute to the return value of render:

<input ref="myInput" />

In other code, obtain the support instance through this.refs:

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

Example:

Use this to get the current React component, or use ref to get the component reference, as follows:

class MyComponent extends React.Component {
  handleClick() {
    // 使用原生的 DOM API 获取焦点
    this.refs.myInput.focus();  }
  render() {
    //  当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
    return (
      <div>
        <input type="text" ref="myInput" />
        <input
          type="button"
          value="点我输入框获取焦点"
          onClick={this.handleClick.bind(this)}
        />
      </div>    );  }}
 ReactDOM.render(
  <MyComponent />,  document.getElementById(&#39;example&#39;));

In the example, we get the input box The reference of the supporting instance, the input box gets the focus after the child clicks the button.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of What are refs in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn