首頁 >web前端 >js教程 >在打字稿中擴展HTML元素的屬性

在打字稿中擴展HTML元素的屬性

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌原創
2025-02-08 11:09:09345瀏覽

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