在 React 中,useRef 是一种用于获取 DOM 元素或保存任意值的 Hook。它的用法类似于 useState,但是不会触发重新渲染组件。如果需要在 Class 组件中使用 useRef,可以使用 React.createRef() 方法来创建一个 ref 对象,然后在组件中使用该对象。

以下是一个使用 useRef 的函数组件示例:

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef(null);

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

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus input</button>
    </div>
  );
}

在上面的代码中,我们创建了一个 inputRef 对象,并将其作为 ref 属性传递给 <input> 元素。然后,在 handleClick 函数中,我们使用 inputRef.current 来访问 input 元素,并调用 focus() 方法将焦点设置到该元素上。

在 Class 组件中,我们可以使用 React.createRef() 方法来创建一个 ref 对象,并在组件中使用该对象。以下是一个使用 createRef 的 Class 组件示例:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

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

  render() {
    return (
      <div>
        <input ref={this.inputRef} type="text" />
        <button onClick={this.handleClick}>Focus input</button>
      </div>
    );
  }
}

在上面的代码中,我们在 constructor 中使用 React.createRef() 方法创建了一个 inputRef 对象,并将其保存在组件的实例属性中。然后,在 handleClick 函数中,我们使用 this.inputRef.current 来访问 input 元素,并调用 focus() 方法将焦点设置到该元素上。

react中useRef,对应在class组件的使用方式

原文地址: http://www.cveoy.top/t/topic/uhj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录