React Ref TypeScript 用法

React Ref 是 React 提供的一种方式,允许我们访问 DOM 节点或者在 render 方法中创建的 React 元素,通常情况下,我们会避免直接操作 DOM,而选择使用 React 提供的状态(state)和属性(props)来更新视图,有些情况下,我们需要直接操作 DOM,这时候就需要使用 Refs。

React Ref TypeScript 用法
(图片来源网络,侵删)

在 TypeScript 中,我们可以使用 React.RefObject<T> 类型来声明一个 Ref,这个类型表示一个可以附加到任何可渲染对象的引用,例如一个 DOM 元素或者一个类组件实例,下面是一个简单的例子:

import React, { useRef } from 'react';
function TextInputWithFocusButton() {
  const inputEl = useRef<HTMLInputElement>(null);
  const onButtonClick = () => {
    // current 属性会被初始化为存储在 useRef 中的值
    inputEl.current?.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>聚焦输入框</button>
    </>
  );
}

在这个例子中,我们使用 useRef 创建了一个 Ref,并将其存储在 inputEl 变量中,我们将这个 Ref 附加到 <input> 元素上,当用户点击按钮时,我们可以通过 inputEl.current 访问到这个元素,并调用 focus 方法使其获得焦点,需要注意的是,我们需要使用可选链操作符(?.)来确保 current 属性存在,这是因为在某些情况下,例如组件卸载时,useRef 存储的值可能会被清除。

除了 useRef,我们还可以使用 createRef API 来创建一个 Ref,下面是一个例子:

import React, { useRef, createRef } from 'react';
function TextInputWithFocusButton() {
  const inputEl = createRef<HTMLInputElement>();
  const onButtonClick = () => {
    inputEl.current?.focus();
  };
  return (
    <>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>聚焦输入框</button>
    </>
  );
}

在这个例子中,我们使用 createRef 创建了一个 Ref,并将其存储在 inputEl 变量中,我们将这个 Ref 附加到 <input> 元素上,当用户点击按钮时,我们可以通过 inputEl.current 访问到这个元素,并调用 focus 方法使其获得焦点,同样需要注意的是,我们需要使用可选链操作符来确保 current 属性存在。

我们可能需要在多个组件之间共享一个 Ref,为了实现这一点,我们可以将 Ref 作为 prop 传递给子组件,下面是一个例子:

import React, { useRef, forwardRef } from 'react';
const FancyTextInput = forwardRef<HTMLInputElement, string>((props, ref) => {
  return <input ref={ref} type="text" className="fancy" />;
});
function App() {
  const inputEl = useRef<HTMLInputElement>(null);
  const handleButtonClick = () => {
    inputEl.current?.focus();
  };
  return (
    <div>
      <FancyTextInput ref={inputEl} />
      <button onClick={handleButtonClick}>聚焦输入框</button>
    </div>
  );
}

在这个例子中,我们使用 forwardRef API 创建了一个名为 FancyTextInput 的自定义组件,这个组件接受一个名为 ref 的 prop,并将其附加到内部的 <input> 元素上,我们在 App 组件中使用这个自定义组件,并将一个 Ref 作为 prop 传递给它,当用户点击按钮时,我们可以通过 inputEl.current 访问到这个元素,并调用 focus 方法使其获得焦点,需要注意的是,由于我们使用了 forwardRef,所以我们不需要使用可选链操作符来确保 current 属性存在。

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/477883.html

(0)
未希新媒体运营
上一篇 2024-04-15 09:30
下一篇 2024-04-15 09:32

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入