本文节选自《释放TypeScript的威力》,将向您展示如何在TypeScript中扩展HTML元素的属性。在大型应用中,我们经常构建基于标准HTML元素的组件,例如自定义按钮,或组合标签和输入字段的组件。
TypeScript要求显式定义组件接受的属性,这对于每个属性来说都可能很繁琐。为了匹配React中HTML元素使用的属性,可以使用React.ComponentProps
。要排除某些属性,可以使用Omit
实用程序类型。
要扩展组件的属性,可以使用交集类型。这允许组件接受HTML元素的所有属性以及其他附加属性。这对于根据当前主题更改样式的组件或向标准HTML元素添加新功能非常有用。
方法一:扩展单个HTML元素的属性
让我们创建一个具有应用内样式的自定义按钮组件。在JavaScript中,我们可以这样做:
const Button = (props) => { return <button {...props} />; };
在TypeScript中,我们可以添加必要的属性,例如children
:
const Button = ({ children }: React.PropsWithChildren) => { return <button>{children}</button>; };
但这很繁琐。我们可以使用React.ComponentProps
来匹配HTML button
元素的属性:
const Button = (props: React.ComponentProps<'button'>) => { return <button {...props} />; };
但如果用户传递className
属性,它会覆盖我们的样式。我们可以使用Omit
排除特定属性:
type ButtonProps = Omit<React.ComponentProps<'button'>, 'className'>; const Button = (props: ButtonProps) => { return <button {...props} />; };
或者,我们可以使用clsx
库来管理类名:
import React from 'react'; import clsx from 'clsx'; type ButtonProps = React.ComponentProps<'button'>; const Button = ({ className, ...props }: ButtonProps) => { return <button className={clsx('button', className)} {...props} />; };
要扩展属性,可以使用交集类型:
type ButtonProps = React.ComponentProps<'button'> & { variant?: 'primary' | 'secondary'; };
现在,Button
组件接受button
元素的所有属性,以及额外的variant
属性。
方法二:创建组合组件
另一个常见的组件是组合标签和输入元素的组件:
type LabeledInputProps = React.ComponentProps<'input'> & { label: string; }; const LabeledInput = ({ id, label, ...props }: LabeledInputProps) => { return ( <> <label htmlFor={id}>{label}</label> <input id={id} {...props} /> </> ); };
这样,我们就可以轻松地复用和扩展标准HTML元素的功能,提高代码的可维护性和可重用性。
本文节选自《释放TypeScript的威力》,更多内容请访问SitePoint Premium或电子书零售商。
以上是在打字稿中扩展HTML元素的属性的详细内容。更多信息请关注PHP中文网其他相关文章!