簡體   English   中英

如何使用 props 使用 scss 設置組件樣式(不使用樣式化組件)

[英]How to style a component with scss using props (without using styled components)

我創建了一個 UI 庫,其中包含多個組件。 這些組件不能在前端進行更改,並且它們的所有變體都必須在庫中定義,因此它們只需要將 props 傳遞給組件。

對於圖書館,我使用 React + 故事書 + typescript + 匯總。

我不想使用樣式組件,因為項目必須快速且不冗長。 它需要具有良好的性能和快速的響應。

此外,我不應該使用任何 UI 庫(如材質 UI 或引導程序)。

例如:前端使用

<Button size='small' color='primary'> Test </Button>

UI 庫中的組件:

import React, { MouseEventHandler } from 'react';
import './Button.scss'

export interface ButtonProps {
    children: React.ReactNode,
    color: 'primary' | 'secondary',
    disabled?: boolean,
    size?: 'small' || 'large',
    onClick?: MouseEventHandler<HTMLButtonElement>
}


const Button: React.FC<ButtonProps> = ({size, color, disabled, children, onClick, ...props}) => {  

    return (
        <button type="button">
            {children} 
        </button>
    )
} 

export default Button

我想知道如何處理這些屬性,以便能夠傳遞不同的大小、colors 和屬性,並且能夠在不使用樣式組件的情況下在 scss 中進行更改。

我還考慮過為尺寸和 colors 創建 ts ENUM,但我不知道該怎么做,也不知道這對這個項目是否有意義。 我還想知道在這種情況下使用 scss 的最佳結構。 (如何在 scss 中創建這些不同的 styles)。

我還想知道如何在我的庫中創建全局樣式來創建 colors 和字體大小變量。

這是我的項目文件夾結構:

項目結構

從我看你已經可以消費children了。 對於與button的行為方式相關的屬性,您可以簡單地使用Spread 語法 對於每個樣式屬性,您可以創建一個相關的class並在您的 SCSS 文件中獲取它:

const Button: React.FC<ButtonProps> = ({ size, color, children, ...othersProps }) => {
  return (
    <button  {...othersProps} type="button" class={`button ${size} ${color}`}>
      {children}
    </button>
  );
 };
 
 export default Button;
.button {
  &.small {
    font-size: 13px;
  }
  &.large {
    font-size: 20px; 
  }
  &.primary {
    color: red;   
  }
  &.secondary {
    color: blue;     
  }
}

最后,關於您的其他問題,如果可以的話,我建議您從小處着手,嘗試一些可行的方法,然后您可以重新格式化您的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM