在HarmonyOS NEXT的原子化服务架构下,组件设计已成为开发效率与用户体验的核心。本文将深入剖析十大核心组件,涵盖UI构建、数据交互、设备协同三大维度,通过20+企业级案例揭示组件的深度用法。
Button({ type: ButtonType.Capsule })
.backgroundColor('#FF007D')
.stateEffect(true)
.onClick(() => {
// 点击波纹动画
})
.hoverEffect(HoverEffect.Highlight)
.disabled(this.isDisabled) // 动态禁用状态
Text() {
Span('红色文字')
.fontColor(Color.Red)
Span(' + ')
Span('下划线')
.decoration({ type: TextDecorationType.Underline })
}
.fontSize(20)
.lineHeight(30)
.textOverflow({ overflow: TextOverflow.Ellipsis })
Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap }) {
ForEach(this.items, (item) => {
Column() {
// 子组件
}.flexGrow(1) // 等分扩展
})
}
.justifyContent(FlexAlign.SpaceBetween)
.padding({ top: 20, bottom: 20 })
Stack() {
// 背景层
Image($r('app.media.background'))
.width('100%')
// 内容层
Column() {
// 主内容
}
// 悬浮按钮
Button('+')
.position({ x: '90%', y: '85%' })
.zIndex(999)
}
List({ space: 20 }) {
LazyForEach(this.dataSource, (item) => {
ListItem() {
ItemComponent({ item })
}
}, (item) => item.id.toString())
}
.edgeEffect(EdgeEffect.None) // 禁用overscroll效果
.cachedCount(5) // 预渲染数量
Tabs({ index: this.selectedIndex }) {
TabContent() {
// 页面1
}.tabBar('推荐')
TabContent() {
// 页面2
}.tabBar('关注')
}
.onChange((index: number) => {
// 联动动画
animateTo({ duration: 300 }, () => {
this.selectedIndex = index;
})
})
Canvas(this.context)
.width('100%')
.height('100%')
.onReady(() => {
// 渲染循环
setInterval(() => {
this.context.clearRect(0, 0, width, height)
this.drawGameFrame()
}, 16)
})
private drawGameFrame() {
this.context.beginPath()
this.context.arc(x, y, 10, 0, Math.PI * 2)
this.context.fillStyle = '#FF0000'
this.context.fill()
}
Video({
src: 'https://example.com/video.mp4',
controller: this.videoController
})
.controls(true)
.autoPlay(false)
.onPrepared(() => {
// 获取视频元数据
const duration = this.videoController.duration
})
.onError(() => {
// 异常处理
})
RemoteView({
bundleName: 'com.example.remote',
abilityName: 'MainAbility',
componentName: 'WeatherWidget'
})
.onComplete(() => {
console.log('远程组件加载完成')
})
.onError((err) => {
console.error('加载失败:', err)
})
// 创建分布式数据对象
const dataObject = distributedData.create({
key: 'sharedData',
data: { value: 0 },
conflictResolver: (local, remote) => {
return remote.value > local.value ? remote : local
}
})
// 监听数据变化
dataObject.on('change', (newData) => {
this.value = newData.value
})
@Gesture({
tap: { count: 2 },
pan: { direction: PanDirection.All },
pinch: { distance: { min: 0.5, max: 10 } }
})
private gestureGroup: GestureGroup = new GestureGroup()
private setupGestures() {
this.gestureGroup
.onTap(() => { /* 双击处理 */ })
.onPanUpdate((event) => { /* 拖拽处理 */ })
.onPinch((event) => { /* 缩放处理 */ })
}
Web({ src: 'https://example.com', controller: this.webController })
.javaScriptAccess(true)
.onPageEnd(() => {
// 注入自定义脚本
this.webController.runJavaScript('window.Harmony = {};')
})
.onMessage((event) => {
// 处理JS消息
if (event.message === 'getToken') {
this.webController.postMessage('token', this.userToken)
}
})
@Component
export struct EnterpriseButton {
@Prop label: string = 'Button'
@Link @Watch('onPress') isActive: boolean
private onPress() {
// 业务逻辑
}
build() {
Button(this.label)
.onClick(() => this.onPress())
}
}
随着HarmonyOS NEXT的组件生态持续丰富,掌握这些核心组件的深度用法将成为开发者的核心竞争力。