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注解。

相关推荐
哈__15 分钟前
ReactNative for Harmony 项目鸿蒙化三方库集成实战:react-native-safe-area-context
react native·react.js·harmonyos
Goway_Hui20 分钟前
【开源鸿蒙跨平台开发--KuiklyUI--03】KuiklyUI 入门实战:从零打造高性能跨平台 Todo 应用
华为·开源·harmonyos·kuikly
waeng_luo39 分钟前
如何利用AI提高鸿蒙开发效率:从Rules到智能开发实践
人工智能·华为·harmonyos
哈__43 分钟前
ReactNative for Harmony项目鸿蒙化三方库集成实战:react-native-elements
react native·react.js·harmonyos
哈__44 分钟前
ReactNative for Harmony 项目鸿蒙化三方库集成实战:@react-native-ohos/react-native-picker
react native·react.js·harmonyos
ITUnicorn1 小时前
【HarmonyOS6】简易计数器开发
华为·harmonyos·arkts·鸿蒙·harmonyos6
前端不太难2 小时前
HarmonyOS 游戏里的“假异步”,为什么会卡
游戏·状态模式·harmonyos
摘星编程2 小时前
React Native鸿蒙:自定义usePluralize复数形式转换
react native·react.js·harmonyos
熊猫钓鱼>_>2 小时前
【开源鸿蒙跨平台开发先锋训练营】Day 8:鸿蒙 Next + React Native 实战:打造丝滑的四Tab底部导航体验
react native·开源·list·tab·harmonyos·鸿蒙·next
Facechat2 小时前
鸿蒙开发入坑篇(十二):通知与后台任务 (Notifications)
华为·harmonyos