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
属性的正确类型是什么?
使用
React.RefObject
:
function MyInput({placeholder, ref}: {
placeholder: string;
ref: React.RefObject<HTMLInputElement>;
}) {
return <input placeholder={placeholder} ref={ref} />
}