带有 'as' 属性的多态组件
为 'as' 属性定义类型,使 Button 可以渲染为 或 ,同时保留正确的属性类型。
带有 'as' 属性的多态组件 是 CoddyKit 上的免费 React Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Academy 课程共包含 4 节课。
什么是多态组件
多态组件根据 as 属性渲染为不同的 HTML 元素或组件——例如,Button 可以渲染为 <a> 或 <button>,同时保持正确的 TypeScript 类型。
简单的 as 属性(不使用 TypeScript)
一种不使用泛型的基础多态实现——会失去类型安全,但能够展示这一概念。
function Box({ as: Tag = 'div', children, ...props }) {
return <Tag {...props}>{children}</Tag>;
}
// Usage:
<Box as="section" className="hero">...</Box>
<Box as="article">...</Box>使用泛型为 as 属性添加类型
添加泛型类型参数,为 as 所渲染的任意元素推断正确的属性。
type PolymorphicProps<E extends React.ElementType> = {
as?: E;
} & Omit<React.ComponentPropsWithoutRef<E>, 'as'>;
function Box<E extends React.ElementType = 'div'>({
as,
...props
}: PolymorphicProps<E>) {
const Tag = as ?? 'div';
return <Tag {...props} />;
}支持 ref
在保留多态类型的同时,添加 forwardRef 支持。
type PolymorphicRef<E extends React.ElementType> = React.ComponentPropsWithRef<E>['ref'];
type PolymorphicPropsWithRef<E extends React.ElementType, P = {}> = P &
Omit<React.ComponentPropsWithRef<E>, keyof P> & { as?: E };
const Button = React.forwardRef(
<E extends React.ElementType = 'button'>(
{ as, ...props }: PolymorphicPropsWithRef<E>,
ref: PolymorphicRef<E>
) => {
const Tag = as ?? 'button';
return <Tag ref={ref} {...props} />;
}
);TypeScript 类型推断实战
当您设置 as='a' 时,TypeScript 知道该组件接受 href 和 target 等链接专用属性,但不接受 disabled 等按钮专用属性。
// TypeScript allows href because as='a':
<Box as="a" href="https://example.com">Link</Box>
// TypeScript errors if you pass href to a div:
<Box as="div" href="...">Error!</Box> // TS: href is not a valid div prop扩展自定义属性
通过将组件专用属性展开到类型定义中,在多态基础上添加这些属性。
type TextProps<E extends React.ElementType> = PolymorphicProps<E> & {
size?: 'sm' | 'md' | 'lg';
weight?: 'normal' | 'bold';
};
function Text<E extends React.ElementType = 'p'>({
as,
size = 'md',
weight = 'normal',
className,
...props
}: TextProps<E>) {
const Tag = as ?? 'p';
return (
<Tag
className={[`text-${size}`, `font-${weight}`, className].filter(Boolean).join(' ')}
{...props}
/>
);
}实际使用场景:渲染为 RouterLink 的链接
如果提供了 to,Button 就渲染为 React Router 的 Link;否则渲染为普通按钮。
import { Link } from 'react-router-dom';
type ButtonProps =
| { to: string; href?: never } & React.ComponentPropsWithoutRef<typeof Link>
| { href: string; to?: never } & React.ComponentPropsWithoutRef<'a'>
| { to?: never; href?: never } & React.ComponentPropsWithoutRef<'button'>;
function Button({ to, href, ...props }: ButtonProps) {
if (to) return <Link to={to} {...props} />;
if (href) return <a href={href} {...props} />;
return <button type="button" {...props} />;
}设计系统文本组件
多态 Text 组件默认渲染为 <p>,但也可以渲染为 h1–h6、span 或 label。
<Text as="h1" size="xl">Page Title</Text>
<Text as="span" weight="bold">Inline bold</Text>
<Text as="label" htmlFor="email">Email</Text> // htmlFor is valid because as='label'对 as 属性的约束
使用 extends React.ElementType,以同时接受 HTML 元素字符串('div'、'a')和 React 组件。
function Card<E extends React.ElementType = 'div'>({ as, ...props }: PolymorphicProps<E>) {
const Tag = as ?? 'div';
return <Tag {...props} />;
}
// Works with HTML elements:
<Card as="section" aria-label="Products" />
// Works with React components:
<Card as={motion.div} animate={{ opacity: 1 }} />避免常见问题
不要将 as 属性展开到元素上(它不是有效的 HTML 属性)。在展开其余属性之前,务必先将它解构出来。
// Bad:
function Box({ as: Tag = 'div', ...props }) {
return <Tag as={...} {...props} />; // 'as' attribute on div is invalid HTML
}
// Good:
function Box({ as: Tag = 'div', ...props }) {
return <Tag {...props} />; // 'as' is used to pick Tag, not passed to element
}性能注意事项
多态组件的性能开销极小——as 属性只是一个保存元素类型字符串或组件引用的变量。
快速检查
在多态组件中,为什么应该先解构出 as 属性,再将其余属性展开到元素上?
回顾
多态组件使用泛型 as?: E extends React.ElementType 属性,可以渲染为任意元素,同时保留正确的 TypeScript 属性类型。在展开其余属性之前,先解构出 as。使用 React.ComponentPropsWithoutRef 将所有元素专用属性包含在类型中。
常见问题解答
「带有 'as' 属性的多态组件」课时是免费的吗?
是的 — 「带有 'as' 属性的多态组件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Academy 课程共包含 4 节课。
「带有 'as' 属性的多态组件」这节课中我会学到什么?
为 'as' 属性定义类型,使 Button 可以渲染为 或 ,同时保留正确的属性类型。 你通过在浏览器中直接运行的动手代码来练习 React Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 React Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 React Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「带有 'as' 属性的多态组件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 React Academy 课中编写并运行代码吗?
能。每节 React Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 组件变体的可辨识联合类型
- React 中的条件类型与映射类型
- 带有 'as' 属性的多态组件
- 类型安全的表单与 API 响应契约