Harmony AttributeModifier 基本使用

csharp 复制代码
declare interface AttributeModifier<T> {

    /**
     * Defines the normal update attribute function.
     */
    applyNormalAttribute?(instance: T): void;
    /**
     * Defines the pressed update attribute function.
     */
    applyPressedAttribute?(instance: T): void;
    /**
     * Defines the focused update attribute function.
     */
    applyFocusedAttribute?(instance: T): void;
    /**
     * Defines the disabled update attribute function.
     */
    applyDisabledAttribute?(instance: T): void;
    /**
     * Defines the selected update attribute function.
     */
    applySelectedAttribute?(instance: T): void;
}

AttributeModifier 定义的方法会在组件切换到对应的状态的时候出发点。

基本用法:1 实现AttributeModifier 类型T的指定决定于这个Modifier最终作用在哪个组件上。通过对应组件的 attributeModifier 方法的参数就可以知道具体的类型。

scss 复制代码
class ButtonModifierImpl implements  AttributeModifier<ButtonModifier> {
  isClick = false;
  applyPressedAttribute(instance: ButtonModifier): void {
    if(this.isClick){
      instance.backgroundColor(Color.Red)
    }else {
      instance.backgroundColor(Color.Blue)
    }
  }

  applyNormalAttribute(instance: ButtonModifier): void {
    if(this.isClick){
      instance.backgroundColor(Color.Red)
    }else {
      instance.backgroundColor(Color.Blue)
    }
  }
}

2 使用 我这里是作用在Button上,所以T的类型就是ButtonModifier

less 复制代码
@State
buttonModifier : ButtonModifierImpl =  new ButtonModifierImpl();
kotlin 复制代码
Column(){
  Button("测试Modifier")
    .attributeModifier(this.buttonModifier)
  Button("测试Modifier")
    .backgroundColor(Color.Blue)
    .onClick((event)=>{
     this.buttonModifier.isClick = !this.buttonModifier.isClick
    })
}

2.1 当Button 触发不同的回调的时候,就会设置新的样式。比如点击的时候。 2.2 也可以在Modifier中定义变量。当变量发生改变的时候,也会触发回调。注意的是buttonModifier必须使用@State注解。

相关推荐
less_121383 小时前
HarmonyOS WPS Open SDK:打开时配置水印与修订模式
华为·harmonyos·wps
HarmonyOS_SDK6 小时前
差异化推送消息能力,助力腕上支付业务闭环
harmonyos
小雨青年9 小时前
【HarmonyOS 7 沉浸光感深度实战】 03 五档 ImmersiveStyle 到底怎么选
华为·harmonyos
云端漫步198711 小时前
HarmonyOS NEXT AI 智能生活助手:性能优化
华为·性能优化·生活·harmonyos
云端漫步198711 小时前
HarmonyOS NEXT AI 智能生活助手:统一 AIService 封装
人工智能·华为·生活·harmonyos
云端漫步198714 小时前
HarmonyOS NEXT AI 智能生活助手:设置中心开发
人工智能·华为·生活·harmonyos
用户09340777351414 小时前
HarmonyOS WPS Open SDK 实践:关文档后怎么把结果拿回本应用
harmonyos
less_1213815 小时前
HarmonyOS WPS Open SDK:用 extraOptions 管住分享打印与导出
深度学习·harmonyos·wps
less_1213816 小时前
HarmonyOS WPS Open SDK:OpenFileRequest 只读与可编辑模式控制
深度学习·harmonyos·wps
程序员黑豆19 小时前
使用AI编程开发鸿蒙应用:从环境搭建到实战示例
前端·harmonyos