文章目錄
- 一、樣式復用
- 1.1 @Styles修飾符
- 1.2 @Extend修飾符
- 二、多態樣式
一、樣式復用
在頁面開發過程中,會出出現大量重復的樣式設置代碼,可以使用@Styles和@Extend修飾符將幫助我們進行樣式復用。
1.1 @Styles修飾符
@Styles裝飾器可以將多條樣式設置提煉成一個方法,直接在組件聲明的位置調用。通過@Styles裝飾器可以快速定義并復用自定義樣式。
@Styles
function payWechatStyle(){.width('100%').height(50).borderRadius(4).backgroundColor("#00c168").onClick(()=>{promptAction.showToast({message: '微信支付成功'})})
}@Entry
@Component
struct StylesCase {@StylespayAliStyle(){.width('100%').height(50).borderRadius(4).backgroundColor("#ff1256e0").onClick(()=>{promptAction.showToast({message: '支付寶支付成功'})})}build() {Column({space: 20}){Row(){Button("微信支付", { type: ButtonType.Normal }).payWechatStyle().fontColor(Color.White)}.padding(20)Row(){Button("支付寶支付", { type: ButtonType.Normal }).payAliStyle().fontColor(Color.White)}.padding(20)Row(){Button("支付寶支付", { type: ButtonType.Normal }).payAliStyle().fontColor(Color.White)}.padding(20)}}
}
使用說明:
- 僅支持通用屬性和通用事件
- 可以定義在組件內(不需加function)或全局
- 同時在組件內或全局定義時,組件內生效
限制條件:
- 方法中不能有參數
- 不支持導出
1.2 @Extend修飾符
@Extend修飾符針對某類組件進行樣式擴展,同樣為了復用樣式。
@Entry
@Component
struct ExtendCase {build() {Column({space: 20}){Button('支付寶支付').payButton('alipay')Button('微信支付').payButton('wechat')}.padding(20).width('100%')}
}@Extend(Button)
function payButton(type: 'alipay'|'wechat'){.type(ButtonType.Normal).fontColor(Color.White).width('100%').height(50).borderRadius(4).backgroundColor(type == 'wechat'? "#00c168" : "#ff1256e0").onClick(()=>{if (type == 'alipay') {promptAction.showToast({message:"支付寶支付成功"})}else{promptAction.showToast({message:"微信支付成功"})}})
}
使用說明:
- 只能定義在全局函數
- 指定組件,只支持指定組件的私有屬性、私有事件
- 函數支持傳參
限制條件:
- 不支持導出
二、多態樣式
多態樣式(stateStyles)根據組件內部狀態的不同,快速設置不同樣式。
ArkUI提供五種狀態:
- focused:獲焦態
- normal:正常態
- pressed:按壓態
- disabled:不可用態
- selected:選中態
@Entry
@Component
struct StateStylesCase {build() {Column({space: 20}){Row(){Text('你好!鴻蒙')}.padding(20).height(80).border({color: '#f3f4f5',width: 3}).borderRadius(4).stateStyles({normal: {.backgroundColor(Color.White)},pressed: {.backgroundColor('#eee')}}).width('100%')}.padding(20).justifyContent(FlexAlign.Center).width('100%').height('100%')}
}
設置normal和pressed狀態時的背景顏色,按壓時是#eee顏色,松開是白色。
使用說明:
多態樣式只支持通用屬性的設置。