# React 19 TypeScript 模式
React 19 引入了重大变更和新 API,需要更新 TypeScript 模式。
## ref 作为属性 (不再需要 forwardRef)
React 19 允许将 ref 作为常规属性传递 — forwardRef 已弃用但仍可使用。
typescript
// ✅ React 19 - ref 作为属性
type InputProps = {
ref?: React.Ref;
label: string;
} & React.ComponentPropsWithoutRef;
export function Input({ ref, label, ...props }: InputProps) {
return (
);
}
// 使用方式
function Form() {
const inputRef = useRef(null);
return (
);
}
typescript
// ❌ 旧模式 (仍有效,但没必要)
import { forwardRef } from 'react';
type InputProps = {
label: string;
} & React.ComponentPropsWithoutRef;
export const Input = forwardRef(
({ label, ...props }, ref) => {
return (
);
}
);
Input.displayName = 'Input';
### 带有 ref 的泛型组件
typescript
type SelectProps = {
ref?: React.Ref;
options: T[];
value: T;
onChange: (value: T) => void;
getLabel: (option: T) => string;
};
export function Select({ ref, options, value, onChange, getLabel }: SelectProps) {
return (
{
const selected = options.find((opt) => getLabel(opt) === e.target.value);
if (selected) onChange(selected);
}}
>
{options.map((opt) => (
{getLabel(opt)}
))}
);
}
### 将 ref 与其他属性结合
typescript
type ButtonProps = {
ref?: React.Ref;
variant?: 'primary' | 'secondary';
size?: 'sm' | 'md' | 'lg';
} & React.ComponentPropsWithoutRef;
export function Button({
ref,
variant = 'primary',
size = 'md',
className,
children,
...props
}: ButtonProps) {
return (
);
}
## useActionState - 表单状态管理