【最新】鸿蒙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
    })
  }
}

总结

  • 开发过程中根据具体需求选择合适的修饰器
  • 合理设计组件结构,避免过度嵌套
  • 页面加载过程中避免不必要的状态更新
  • 在同一项目中尽量保持修饰器使用的一致性
  • 开发过程中为复杂的修饰器使用添加注释说明
相关推荐
爱笑的眼睛117 小时前
深入剖析 HarmonyOS ArkUI 声明式开发:状态管理艺术与最佳实践
华为·harmonyos
安卓开发者8 小时前
鸿蒙NEXT交互机制解析:从输入设备到手势响应的全面指南
microsoft·交互·harmonyos
奶糖不太甜。11 小时前
鸿蒙分布式数据同步失败全解
分布式·华为·harmonyos·数据同步
小小小小小星1 天前
鸿蒙权限相关问题之应用访问网络、文件等功能时崩溃或无响应,日志提示'权限被拒绝'
harmonyos
leon_teacher2 天前
ArkUI核心功能组件使用
android·java·开发语言·javascript·harmonyos·鸿蒙
lisir92 天前
鸿蒙手势实战解析+手势冲突解决策略总结
harmonyos
安卓开发者2 天前
鸿蒙Next图形绘制指南:从基础几何图形到复杂UI设计
ui·华为·harmonyos
开发小能手嗨啊2 天前
鸿蒙开发进阶(HarmonyOS)
harmonyos·鸿蒙·鸿蒙开发·开发教程·纯血鸿蒙·南向开发·北向开发
大土豆的bug记录2 天前
鸿蒙总改变字体大小设置
华为·harmonyos
我爱学习_zwj2 天前
【鸿蒙面试题-6】LazyForEach 懒加载
华为·harmonyos