创建 Refs 的几种方式

Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。

到目前为止,我们有三种方式创建 Refs 。

  1. 回调 Refs

  2. createRef API 的方式

  3. 使用 useRef() hook

回调 Refs

现在有一段代码,需要实现的功能是点击 button 按钮然后给 input 表单获取焦点。代码结构如下:

import React, { Component } from "react";

class CallbackRefExample extends Component {
 constructor(props) {
   super(props);
 }

 render() {
   return (
     <div>
       回调 Refs:
       <br />
       <input type="text" />
       <button>Click</button>
     </div>
   );
 }
}

export default CallbackRefExample;

要实现这个功能,首先需要创建一个回调函数,并通过 ref 属性附加到 React 元素。然后给按钮绑定点击事件即可。

import React, { Component } from "react";


class CallbackRefExample extends Component {
  constructor(props) {
    super(props);
    this.inputElementRef = this.inputElementRef.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  inputElementRef(inputElement) {
    this.inputRef = inputElement;
  }

  handleClick() {
    this.inputRef.focus();
  }

  render() {
    return (
      <div>
        回调 Refs :
        <br />
        <input type="text" ref={this.inputElementRef} />
        <button onClick={this.handleClick}>
          Click
        </button>
      </div>
    );
  }
}

export default CallbackRefExample;

React 将在组件挂载时,会调用 ref 回调函数并传入 DOM 元素,当卸载时调用它并传入 null。

componentDidMountcomponentDidUpdate 触发前,React 会保证 refs 一定是最新的。

createRef API 的方式

在 React 16.3 版本中新增 React.createRef() API 用来创建 Refs 。我们不需要再创建回调函数并将其分配给ref prop。只需通过 React.createRef() 创建一个 ref 并将其存储到某个变量中,然后将此变量分配给DOM元素的ref prop。因此,我们将以相同的示例为例。

import React, { Component } from "react";

export default function CallbackRefApiExample() {
  let inputRef = React.createRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      createRef API 的方式:
      <br />
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>
        Click
      </button>
    </div>
  );
}

当 ref 被传递给 render 中的元素时,对该节点的引用可以在 ref 的 current 属性中被访问。

使用 useRef() hook

Hook 是 React 16.8 的新增特性。React 提供了 React 中内置的 Hook API。useRef 是其中一个,用法类似于React.createRef()。

import React, { useRef } from "react";

export default function UseRefHookExample() {
  let inputRef = useRef(null);
  
  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      使用 useRef() hook:
      <br />
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>
        Click
      </button>
    </div>
  );
}

End

在这里插入图片描述

发布了254 篇原创文章 · 获赞 200 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/wu_xianqiang/article/details/104153645