使用樣式的注意事項

本頁說明使用樣式的最佳做法,確保程式碼集風格一致,並介紹我們設計 API 時遵循的原則。

建議做法

請遵循以下最佳做法:

建議:使用樣式設定視覺效果,並使用修飾符設定行為

使用 Styles API 進行視覺設定 (背景、邊框間距、邊框),並保留修飾符,用於點擊邏輯、手勢偵測或無障礙功能等行為。

建議:在設計系統中公開樣式參數

如果是您自己的自訂設計系統元件,則應在修飾符參數後公開 Style 物件。

@Composable
fun GradientButton(
    modifier: Modifier = Modifier,
    // ✅ DO: for design system components, expose a style modifier to consumers to be able to customize the components
    style: Style = Style
) {
    // Consume the style
}

做法:以樣式取代以視覺效果為準的參數

考慮以單一 Style 參數取代可組合項的參數。 例如:

// Before
@Composable
fun OldButton(background: Color, fontColor: Color) {
}

// After
// ✅ DO: Replace visual-based parameters with a style that includes same properties
@Composable
fun NewButton(style: Style = Style) {
}

建議:優先處理動畫的樣式

使用內建的 animate 區塊,根據狀態設定樣式並加入動畫,與修飾符相比,可提升效能。

建議:善用「最後寫入者勝出」原則

善用 style 屬性會覆寫而非堆疊的特性。 用途是覆寫預設元件邊框或背景,不必使用多個參數。

不建議的做法

建議不要使用下列模式:

請勿:使用樣式處理互動邏輯

請勿嘗試在樣式中處理 onClick 或手勢偵測。樣式僅限於根據狀態設定視覺效果,因此不應處理業務邏輯,而只應根據狀態顯示不同的視覺效果。

錯誤做法:以預設參數的形式提供預設樣式

樣式參數一律應使用 style: Style = Style 宣告:

@Composable
fun BadButton(
    modifier: Modifier = Modifier,
    // ❌ DON'T set a default style here as a parameter
    style: Style = Style { background(Color.Red) }
) {
}

如要加入「default」參數,請合併傳入的參數樣式與定義的預設值:

@Composable
fun GoodButton(
    modifier: Modifier = Modifier,
    // ✅ Do: always pass it as a Style, do not pass other defaults
    style: Style = Style
) {
    // ...
    val defaultStyle = Style { background(Color.Red) }
    // ✅ Do Combine defaults inside with incoming parameter
    Box(modifier = modifier.styleable(styleState, defaultStyle, style)) {
      // your logic
    }
}

請勿:將樣式參數提供給以版面配置為基礎的可組合函式

雖然您可以為任何可組合函式提供樣式,但版面配置或畫面層級的可組合函式不應接受樣式,因為從消費者的角度來看,不清楚樣式在這個層級的作用。樣式是為元件設計,不一定適用於版面配置。