React 中写 TypeScript
React 的 TS 模板已成标配:React.FC<Props> 或直接给函数组件写 props 参数类型;事件对象的类型写 React.ChangeEvent<HTMLInputElement>,泛型参数精确到具体元素。
常用四项:useState<string>(初值为 null 时必须显式写)、useRef<HTMLInputElement>(null)、React.ReactNode(children 类型)、ComponentProps<'button'>(继承原生标签属性)。
- 函数组件:function C(props: Props) 或 React.FC
- 事件类型:React.ChangeEvent
精确到元素 - useState 初值可为 null 时必须显式泛型;useRef 泛型绑 DOM
TS
import { useState, useRef } from 'react';
interface Props {
title: string;
onSubmit?: (text: string) => void; // 可选回调
}
function TodoInput({ title, onSubmit }: Props) {
// 初值 null 时必须显式标注联合类型
const [text, setText] = useState<string | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setText(e.target.value);
};
const handleSubmit = () => {
if (text && onSubmit) onSubmit(text);
inputRef.current?.focus(); // ? 处理 ref 可能为 null
};
return (
<div>
<h3>{title}</h3>
<input ref={inputRef} onChange={handleChange} />
<button onClick={handleSubmit}>添加</button>
</div>
);
}JS
// JSX + 类型编译后:类型全擦除,JSX 转成 React.createElement(或 jsx 运行时) import { useState, useRef } from 'react'; function TodoInput({ title, onSubmit }) { const [text, setText] = useState(null); const inputRef = useRef(null); const handleChange = (e) => { setText(e.target.value); }; const handleSubmit = () => { if (text && onSubmit) onSubmit(text); if (inputRef.current) inputRef.current.focus(); }; return /*#__PURE__*/ React.createElement( 'div', null, /*#__PURE__*/ React.createElement('h3', null, title), /*#__PURE__*/ React.createElement('input', { ref: inputRef, onChange: handleChange }), /*#__PURE__*/ React.createElement('button', { onClick: handleSubmit }, '添加') ); }
本节要点React 组件 props 用 interface;事件、useState、useRef 三处泛型是日常高频写法。




