第一次接触鸿蒙应用开发时,很多人会被其"一次开发,多端部署"的理念所吸引。作为面向全场景的分布式操作系统,鸿蒙的UI框架采用声明式开发范式,这与传统Android的命令式编程有本质区别。我在实际项目中最深刻的体会是:理解这种编程思维转变,比单纯记忆API更重要。
开发环境搭建建议选择最新版DevEco Studio 3.1,安装时注意勾选OpenHarmony SDK。新建工程时会面临两种模式选择:
这里有个容易踩的坑:如果后续要使用高级分布式能力,必须选择Stage模型。我团队曾有个项目因初期选错模型,导致后期重构耗费两周时间。
在ets/components目录下新建组件文件,命名建议采用大驼峰式(如CustomInput.ets)。组件结构必须包含三个关键部分:
typescript复制@Component
struct CustomInput {
// 1. 组件状态变量
@State text: string = ''
// 2. 构建函数
build() {
// 3. UI声明
Column() {
TextInput({ text: this.text })
.onChange((value: string) => {
this.text = value
})
}
}
}
父子组件交互主要通过以下装饰器实现:
@Prop:父到子单向同步@Link:父子双向绑定@Provide和@Consume:跨层级传递实际项目中,表单验证组件最适合使用@Link装饰器。例如:
typescript复制// 父组件
@State formData: { username: string } = { username: '' }
build() {
CustomInput({ inputValue: $formData.username })
}
// 子组件
@Component
struct CustomInput {
@Link inputValue: string
build() {
TextInput({ text: this.inputValue })
}
}
| 方案 | 适用场景 | 性能影响 | 代码复杂度 |
|---|---|---|---|
| @State + @Link | 组件内状态 | 低 | 低 |
| @Observed | 跨组件状态共享 | 中 | 中 |
| AppStorage | 全局状态 | 高 | 高 |
在电商APP的商品筛选模块中,推荐组合使用@Observed和@ObjectLink实现复杂对象监听:
typescript复制@Observed
class FilterModel {
priceRange: [number, number] = [0, 1000]
// ...其他筛选条件
}
@Component
struct FilterComponent {
@ObjectLink filter: FilterModel
build() {
Slider({
range: true,
value: this.filter.priceRange
})
}
}
ListItem组件我们在开发社交APP动态流时,通过以下措施将滚动性能提升40%:
typescript复制LazyForEach(this.messageList, (item: Message) => {
ListItem() {
MessageItem({
content: item.content
})
}
}, (item: Message) => item.id.toString())
index.ets和index.scss@since和@version标记推荐目录结构:
code复制components/
├── Button/
│ ├── index.ets
│ ├── index.scss
│ └── __tests__/
└── Modal/
├── index.ets
└── index.scss
问题1:自定义弹窗无法覆盖系统导航栏
解决方案:使用windowClass属性并配置透明背景
typescript复制@Component
struct CustomDialog {
build() {
Column() {
// 弹窗内容
}
.windowClass("transparentWindow")
}
}
问题2:页面返回时状态丢失
解决方案:配合onPageShow生命周期恢复数据
typescript复制@Entry
@Component
struct DetailPage {
@State tempData: object = {}
onPageShow() {
this.tempData = AppStorage.get('cacheData')
}
}
File > Project Structure > Signing Configshdc命令行工具查看日志:bash复制hdc shell hilog -g AppLog
在优化视频播放器组件时,我们通过Trace工具发现:
ImageCache模块实现步骤:
json复制// resources/base/theme/
{
"dark": {
"colorBackground": "#1A1A1A"
},
"light": {
"colorBackground": "#FFFFFF"
}
}
typescript复制@Component
struct ThemeComponent {
@StorageProp('currentTheme') theme: string = 'light'
build() {
Column() {
// 使用资源引用
.backgroundColor($r('app.colorBackground'))
}
}
}
关键API:
distributedObject 分布式数据对象deviceManager 设备管理continuationManager 任务迁移实现Pad和Phone协同编辑的代码片段:
typescript复制// 建立设备连接
const deviceList = deviceManager.getTrustedDeviceListSync()
const distributedObj = distributedObject.createObject({
content: ''
})
// 数据同步
distributedObj.on('change', (data) => {
this.editorContent = data.content
})
对于大型商业项目,推荐采用分层架构:
code复制src/
├── model/ // 数据模型
├── repository/ // 数据仓库
├── component/ // 通用组件
├── view/ // 页面视图
└── utils/ // 工具类
状态管理方案选型参考:
@Observed的自定义Store