如果你想把所有的css属性作为一个类型放在typescript中,你会放什么?

mmvthczy  于 2023-10-22  发布在  TypeScript
关注(0)|答案(2)|浏览(127)

StyleProps用于尺寸和颜色。
我更喜欢所有的风格。
这样我就可以将样式直接传递到组件的特定部分。
我应该用什么来表示所有CSS属性的类型?
如何将样式更改为所有样式?

  1. interface StyleProps{
  2. color?: string;
  3. size?: string;
  4. }
  5. interface TextButtonProps {
  6. buttonStyle?: styleProps;
  7. click: () => void;
  8. text: string;
  9. }
  10. const TextButton = ({ buttonStyle, text, click }: TextButtonProps) => {
fcy6dtqo

fcy6dtqo1#

您可以扩展内置类型CSSStyleDeclaration(ES6 lib类型):

  1. interface StyleProps extends Partial<CSSStyleDeclaration> {
  2. color?: string; // ! not necessary
  3. size?: string;
  4. }
  5. interface TextButtonProps {
  6. buttonStyle?: StyleProps;
  7. click: () => void;
  8. text: string;
  9. }
  10. const TextButton = ({ buttonStyle, text, click }: TextButtonProps) => {

使用Partial是因为内置类型的属性都是必需的。
操场

展开查看全部
ruyhziif

ruyhziif2#

  • 如何扩展元素的内在属性**

示例:本地

  1. interface IButton extends ClassAttributes<HTMLButtonElement> {
  2. // custom properties
  3. size: ESize;
  4. variant: EVariant;
  5. }

示例:React.js

  1. import { ButtonHTMLAttributes } from "react";
  2. interface IButton extends ButtonHtmlAttributes<HTMLButtonElement> {
  3. // custom properties
  4. size: ESize;
  5. variant : EVariant;
  6. }

...
顺便说一句,ESizeEVariantenum的,与理解示例无关。

展开查看全部

相关问题