【最新】鸿蒙Next 装饰器使用方法整理

1. 状态管理修饰器

  • @State :用于组件内的状态管理,状态变化会触发组件重新渲染
scss 复制代码
@Component
struct Counter {
  @State count: number = 0
  
  build() {
    Column() {
      Text(`计数: ${this.count}`)
        .fontSize(20)
      
      Button('增加')
        .onClick(() => {
          this.count++ // 修改状态自动触发重渲染
        })
    }
    .padding(20)
  }
}
  • @Prop :用于父子组件间的数据单向传递。
typescript 复制代码
@Component
struct ChildComponent {
  @Prop message: string
  @Prop @{handler} onMessageChange: (newMessage: string) => void
  
  build() {
    Column() {
      Text(this.message)
      Button('修改消息')
        .onClick(() => {
          this.onMessageChange('新消息')
        })
    }
  }
}

@Entry
@Component
struct ParentComponent {
  @State parentMessage: string = '初始消息'
  
  build() {
    ChildComponent({
      message: this.parentMessage,
      onMessageChange: (newMessage) => {
        this.parentMessage = newMessage
      }
    })
  }
}
  • @Link:用于父子组件间的双向数据绑定。
scss 复制代码
@Component
struct LinkedChild {
  @Link linkedValue: number
  
  build() {
    Column() {
      Text(`链接值: ${this.linkedValue}`)
      Button('增加')
        .onClick(() => {
          this.linkedValue++ // 修改会同步到父组件
        })
    }
  }
}

@Entry
@Component
struct LinkedParent {
  @State parentValue: number = 10
  
  build() {
    LinkedChild({
      linkedValue: $parentValue // 使用$符号创建链接
    })
  }
}
  • @Provide / @Consume :用于跨层级组件的状态共享。
less 复制代码
@Entry
@Component
struct RootComponent {
  @Provide themeColor: string = '#007bff'
  @Provide userName: string = '用户'
  
  build() {
    Column() {
      MiddleComponent()
    }
  }
}

@Component
struct MiddleComponent {
  build() {
    Column() {
      DeepComponent()
    }
  }
}

@Component
struct DeepComponent {
  @Consume themeColor: string
  @Consume userName: string
  
  build() {
    Column() {
      Text(`欢迎, ${userName}`)
        .fontColor(this.themeColor)
    }
  }
}
  • @Observed:用于装饰类,使其成为可观察对象。
typescript 复制代码
@Observed
class UserProfile {
  name: string = ''
  age: number = 0
  email: string = ''
}

@Component
struct ProfileComponent {
  @ObjectLink profile: UserProfile
  
  build() {
    Column() {
      Text(`姓名: ${this.profile.name}`)
      Text(`年龄: ${this.profile.age}`)
      
      Button('更新年龄')
        .onClick(() => {
          this.profile.age++
        })
    }
  }
}
  • @ObjectLink:与@Observed配合使用,实现对象属性的双向绑定。
less 复制代码
@Entry
@Component
struct ObjectLinkExample {
  @State user: UserProfile = new UserProfile()
  
  build() {
    ProfileComponent({
      profile: this.user
    })
  }
}

2. 生命周期修饰器

  • @Builder :用于定义可复用的UI构建函数。
scss 复制代码
@Component
struct BuilderExample {
  @State isLoggedIn: boolean = false
  
  @Builder
  LoginPage() {
    Column() {
      Text('登录页面')
      Button('登录')
        .onClick(() => {
          this.isLoggedIn = true
        })
    }
  }
  
  @Builder
  HomePage() {
    Column() {
      Text('主页')
      Button('退出')
        .onClick(() => {
          this.isLoggedIn = false
        })
    }
  }
  
  build() {
    if (this.isLoggedIn) {
      this.HomePage()
    } else {
      this.LoginPage()
    }
  }
}
  • @Styles :用于定义可复用的样式。
less 复制代码
@Styles
function commonButtonStyle() {
  .width(100)
  .height(40)
  .backgroundColor('#007bff')
  .fontColor('#ffffff')
  .borderRadius(5)
}

@Component
struct StyledButtons {
  build() {
    Column() {
      Button('按钮1')
        .commonButtonStyle()
      
      Button('按钮2')
        .commonButtonStyle()
        .backgroundColor('#28a745')
    }
  }
}
  • @Extend:用于扩展组件的属性。
scss 复制代码
@Extend(Text)
function headingStyle() {
  .fontSize(24)
  .fontWeight(FontWeight.Bold)
  .margin({ bottom: 10 })
}

@Component
struct ExtendedComponent {
  build() {
    Column() {
      Text('标题文本')
        .headingStyle()
      
      Text('普通文本')
        .fontSize(16)
    }
  }
}

3. 监听修饰器

  • @Watch:用于监听状态变化。
less 复制代码
@Component
struct WatchExample {
  @State @Watch('onCountChange') count: number = 0
  @State message: string = '计数器为0'
  
  onCountChange(): void {
    this.message = `计数器变为: ${this.count}`
  }
  
  build() {
    Column() {
      Text(this.message)
      Button('增加')
        .onClick(() => {
          this.count++
        })
    }
  }
}

4. 组件相关修饰器

  • @Entry:标记应用的入口组件。
less 复制代码
@Entry
@Component
struct MainApp {
  build() {
    Column() {
      Text('这是应用入口')
    }
  }
}
  • @Component:标记自定义组件。
scss 复制代码
@Component
struct CustomComponent {
  @Prop title: string = '默认标题'
  
  build() {
    Column() {
      Text(this.title)
        .fontSize(18)
        .fontWeight(FontWeight.Medium)
    }
    .padding(10)
    .backgroundColor('#f0f0f0')
  }
}

5. 状态共享修饰器

  • @LocalStorageProp:用于本地存储的属性绑定。
typescript 复制代码
@Component
struct LocalStorageExample {
  @LocalStorageProp('username') storedUsername: string = '默认用户'
  
  build() {
    Column() {
      Text(`用户名: ${this.storedUsername}`)
      Button('更新用户名')
        .onClick(() => {
          this.storedUsername = '新用户名'
        })
    }
  }
}
  • @LocalStorageLink:用于本地存储的双向绑定。
typescript 复制代码
@Component
struct LocalStorageLinkExample {
  @LocalStorageLink('userSettings') settings: {
    theme: string,
    language: string
  } = {
    theme: 'light',
    language: 'zh'
  }
  
  build() {
    Column() {
      Text(`主题: ${this.settings.theme}`)
      Text(`语言: ${this.settings.language}`)
      
      Button('切换主题')
        .onClick(() => {
          this.settings = {
            ...this.settings,
            theme: this.settings.theme === 'light' ? 'dark' : 'light'
          }
        })
    }
  }
}

6. 路由相关修饰器

  • @BuilderParam:用于传递构建器参数。
scss 复制代码
@Component
struct ParametricComponent {
  @BuilderParam customBuilder: CustomBuilder = this.DefaultBuilder
  
  @Builder
  DefaultBuilder() {
    Text('默认内容')
  }
  
  build() {
    Column() {
      this.customBuilder()
    }
  }
}

@Entry
@Component
struct ParentComponent {
  @Builder
  CustomContent() {
    Text('自定义内容')
  }
  
  build() {
    ParametricComponent({
      customBuilder: this.CustomContent
    })
  }
}

总结

  • 开发过程中根据具体需求选择合适的修饰器
  • 合理设计组件结构,避免过度嵌套
  • 页面加载过程中避免不必要的状态更新
  • 在同一项目中尽量保持修饰器使用的一致性
  • 开发过程中为复杂的修饰器使用添加注释说明
相关推荐
zhanshuo1 小时前
跨设备开发不再难:HarmonyOS 分布式任务管理应用全解析
harmonyos
zhanshuo1 小时前
鸿蒙本地与云端数据双向同步实战:从原理到可运行 Demo 的全流程指南
harmonyos
张风捷特烈1 小时前
鸿蒙纪·Flutter卷#02 | 已有 Flutter 项目鸿蒙化 · 3.27.4 版
android·flutter·harmonyos
humors2213 小时前
鸿蒙示例代码使用心得
华为·实战·harmonyos·鸿蒙·项目·huawei·实操
l and3 小时前
Jenkins 搭建鸿蒙打包
jenkins·harmonyos
沉淀风飛4 小时前
鸿蒙Next在内存管理总结
前端·harmonyos
whysqwhw7 小时前
Hvigor插件实现JS桥接
harmonyos
zhanshuo16 小时前
ArkTS 编译错误不求人:快速定位与修复全攻略
harmonyos
zhanshuo16 小时前
Android 到鸿蒙,不止是兼容:分布式能力改造全攻略
harmonyos