React 19“ref as prop”和 TypeScript

问题描述 投票:0回答:1

React 19 引入了现有

forwardRef
的新替代方案,称为
ref
作为 prop
:

https://react.dev/blog/2024/12/05/react-19#ref-as-a-prop

但不幸的是,博文中提供的示例是用 JavaScript 编写的,而不是 TypeScript::

function MyInput({placeholder, ref}) {
  return <input placeholder={placeholder} ref={ref} />
}

//...
<MyInput ref={ref} />

那么在 TypeScript 中,

ref
属性的正确类型是什么?

reactjs typescript react-props react-forwardref react-19
1个回答
0
投票

使用

React.RefObject

function MyInput({placeholder, ref}: {
  placeholder: string;
  ref: React.RefObject<HTMLInputElement>;
}) {
  return <input placeholder={placeholder} ref={ref} />
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.