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

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

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌原创
2025-02-08 11:09:09427浏览

TypeScript技巧:扩展HTML元素属性

本文节选自《释放TypeScript的威力》,将向您展示如何在TypeScript中扩展HTML元素的属性。在大型应用中,我们经常构建基于标准HTML元素的组件,例如自定义按钮,或组合标签和输入字段的组件。

TypeScript要求显式定义组件接受的属性,这对于每个属性来说都可能很繁琐。为了匹配React中HTML元素使用的属性,可以使用React.ComponentProps。要排除某些属性,可以使用Omit实用程序类型。

要扩展组件的属性,可以使用交集类型。这允许组件接受HTML元素的所有属性以及其他附加属性。这对于根据当前主题更改样式的组件或向标准HTML元素添加新功能非常有用。

方法一:扩展单个HTML元素的属性

让我们创建一个具有应用内样式的自定义按钮组件。在JavaScript中,我们可以这样做:

<code class="language-javascript">const Button = (props) => {
  return <button></button>;
};</code>

在TypeScript中,我们可以添加必要的属性,例如children

<code class="language-typescript">const Button = ({ children }: React.PropsWithChildren) => {
  return <button>{children}</button>;
};</code>

但这很繁琐。我们可以使用React.ComponentProps来匹配HTML button元素的属性:

<code class="language-typescript">const Button = (props: React.ComponentProps<'button'>) => {
  return <button></button>;
};</code>

但如果用户传递className属性,它会覆盖我们的样式。我们可以使用Omit排除特定属性:

<code class="language-typescript">type ButtonProps = Omit<react.componentprops>, 'className'>;

const Button = (props: ButtonProps) => {
  return <button></button>;
};</react.componentprops></code>

或者,我们可以使用clsx库来管理类名:

<code class="language-typescript">import React from 'react';
import clsx from 'clsx';

type ButtonProps = React.ComponentProps<'button'>;

const Button = ({ className, ...props }: ButtonProps) => {
  return <button classname="{clsx('button',"></button>;
};</code>

要扩展属性,可以使用交集类型:

<code class="language-typescript">type ButtonProps = React.ComponentProps<'button'> & {
  variant?: 'primary' | 'secondary';
};</code>

现在,Button组件接受button元素的所有属性,以及额外的variant属性。

方法二:创建组合组件

另一个常见的组件是组合标签和输入元素的组件:

<code class="language-typescript">type LabeledInputProps = React.ComponentProps<'input'> & {
  label: string;
};

const LabeledInput = ({ id, label, ...props }: LabeledInputProps) => {
  return (
    <>
      <label htmlfor="{id}">{label}</label>
      <input id="{id}">
    </>
  );
};</code>

这样,我们就可以轻松地复用和扩展标准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