首页 > web前端 > js教程 > 在打字稿中扩展HTML元素的属性

在打字稿中扩展HTML元素的属性

尊渡假赌尊渡假赌尊渡假赌
发布: 2025-02-08 11:09:09
原创
413 人浏览过

TypeScript技巧:扩展HTML元素属性

本文节选自《释放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元素的功能,提高代码的可维护性和可重用性。

Extending the Properties of an HTML Element in TypeScript Extending the Properties of an HTML Element in TypeScript

本文节选自《释放TypeScript的威力》,更多内容请访问SitePoint Premium或电子书零售商。

以上是在打字稿中扩展HTML元素的属性的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板