React / 系统课时
组件 Props 类型
组件 Props 类型
Props 是组件对外公开的输入接口。为 Props 建立准确类型后,编辑器可以提前提示必填项、限制可选值并校验回调参数,从而把许多运行时问题提前到编码阶段解决。
学习目标
- 使用接口和类型别名描述组件 Props
- 正确声明可选属性、回调函数与 React 节点
- 使用联合类型限制属性的合法取值范围
Props 类型解决什么问题
没有明确类型时,调用方可能漏传必需数据、传入拼错的字符串,或给回调函数使用错误参数。TypeScript 会根据 Props 定义检查 JSX 调用,并在编辑器中提供属性补全,因此 Props 类型既是约束,也是组件使用说明。
对象结构可以使用 interface 或 type。接口适合描述可扩展对象,类型别名更方便组合联合类型、交叉类型和其他类型表达式。项目中不必强行二选一,保持同一模块风格一致即可。
主示例:定义商品卡片 Props
下面代码可直接替换 Vite React TypeScript 项目的 src/App.tsx。示例同时使用接口、类型别名、可选属性和字符串联合类型,并为可选属性提供默认行为。
import type { ReactNode } from 'react';
interface Product {
id: number;
name: string;
price: number;
}
type CardTone = 'info' | 'success' | 'warning';
type ProductCardProps = {
product: Product;
tone?: CardTone;
description?: string;
footer?: ReactNode;
onSelect?: (product: Product) => void;
};
const toneBorder: Record<CardTone, string> = {
info: '#2563eb',
success: '#16a34a',
warning: '#d97706',
};
function ProductCard({
product,
tone = 'info',
description,
footer,
onSelect,
}: ProductCardProps) {
return (
<article
style={{
border: `2px solid ${toneBorder[tone]}`,
borderRadius: 8,
marginBottom: 12,
padding: 16,
}}
>
<h2>{product.name}</h2>
<p>价格:¥{product.price}</p>
{description && <p>{description}</p>}
{footer}
{onSelect && (
<button type="button" onClick={() => onSelect(product)}>
选择商品
</button>
)}
</article>
);
}
export default function App() {
const keyboard: Product = {
id: 1,
name: '机械键盘',
price: 399,
};
const mouse: Product = {
id: 2,
name: '无线鼠标',
price: 159,
};
const handleSelect = (product: Product) => {
window.alert(`已选择:${product.name}`);
};
return (
<main>
<h1>商品列表</h1>
<ProductCard
product={keyboard}
tone="success"
description="支持有线与蓝牙连接"
footer={<small>库存 8 件</small>}
onSelect={handleSelect}
/>
<ProductCard product={mouse} />
</main>
);
}预期结果
页面显示“机械键盘”和“无线鼠标”两张卡片。
第一张卡片使用 success 边框,并显示描述、库存和选择按钮。
第二张卡片省略可选属性,仍按默认 info 样式正常渲染。
点击“选择商品”后,弹窗显示“已选择:机械键盘”。关键边界与常见误区
属性名后的 ? 表示调用方可以不传该属性,但不等于可以传入 null。例如 description?: string 的实际类型是 string | undefined;只有业务确实允许空值时,才应显式写成 string | null。
CardTone 把可选值限制为三个字符串。调用方若写成 tone="green",TypeScript 会在编译阶段报错。相比宽泛的 string,联合类型能保留自动补全,也能防止拼写错误进入运行时。
回调类型应写清参数和返回值。onSelect?: (product: Product) => void 表示组件可能不接收回调;因此渲染按钮和调用函数前都需要先判断它是否存在。
不要用 any 绕过暂时看不懂的类型错误,也不要把所有属性都标成可选。解构 Props 不会自动创建类型,必须在函数参数后标注 ProductCardProps。对于 children、图标或自定义片段,应使用 ReactNode,而不是把它们限制为字符串。