React 19中‘ref as prop’在TypeScript中的正确类型是什么?
React 19 中 "ref as prop" 的 TypeScript 类型定义
React 19 引入的 ref as prop 方案替代了传统的 forwardRef,在 TypeScript 中,你需要给 ref prop 指定正确的类型,核心是使用 React.Ref 类型(它同时支持回调 ref 和对象 ref 两种形式)。
基础用法示例
对于包裹原生 input 的组件,ref 的类型需对应原生元素的类型(比如 HTMLInputElement):
import React from 'react'; type MyInputProps = { placeholder?: string; ref: React.Ref<HTMLInputElement>; }; function MyInput({ placeholder, ref }: MyInputProps) { return <input placeholder={placeholder} ref={ref} />; } // 组件使用示例 function App() { const inputRef = React.useRef<HTMLInputElement>(null); return <MyInput ref={inputRef} placeholder="请输入内容..." />; }
可选 ref 的场景
如果允许组件不传递 ref,可以将 ref 设为可选属性:
type MyInputProps = { placeholder?: string; ref?: React.Ref<HTMLInputElement>; }; function MyInput({ placeholder, ref }: MyInputProps) { return <input placeholder={placeholder} ref={ref} />; }
泛型组件场景
如果组件需要支持不同类型的原生元素,可以用泛型定义 ref 类型:
import React from 'react'; type GenericInputProps<T extends HTMLElement> = { placeholder?: string; ref: React.Ref<T>; type?: React.InputHTMLAttributes<T>['type']; }; function GenericInput<T extends HTMLElement>({ placeholder, ref, type = 'text' }: GenericInputProps<T>) { return <input placeholder={placeholder} ref={ref as React.Ref<HTMLInputElement>} type={type} />; } // 使用时指定元素类型 function App() { const textareaRef = React.useRef<HTMLTextAreaElement>(null); return <GenericInput<HTMLTextAreaElement> ref={textareaRef} placeholder="请输入文本..." />; }
React.Ref<T> 是联合类型,包含 React.RefObject<T> 和 (instance: T | null) => void,因此能同时兼容对象 ref 和回调 ref 的传递。
内容的提问来源于stack exchange,提问作者Mir-Ismaili
相关产品推荐
相关产品推荐

