鸿蒙Ark开发基础知识
数据由AI生成。
一、ArkUI框架概述
鸿蒙ArkUI是华为为HarmonyOS应用开发提供的声明式UI开发框架,采用TypeScript/JavaScript作为开发语言。
// 简单ArkUI组件示例
@Component
struct MyComponent {
build() {
Column() {
Text('Hello ArkUI')
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('Click Me')
.onClick(() => {
console.log('Button clicked!')
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
二、基础组件使用
1. 文本组件
Text('HarmonyOS ArkUI')
.fontSize(20)
.fontColor(Color.Blue)
.textAlign(TextAlign.Center)
.fontWeight(FontWeight.Bold)
2. 按钮组件
Button('Submit', { type: ButtonType.Capsule })
.width(150)
.height(40)
.backgroundColor('#007DFF')
.onClick(() => {
// 处理点击事件
})
3. 图片组件
Image($r('app.media.logo'))
.width(100)
.height(100)
.objectFit(ImageFit.Contain)
三、布局系统
1. 线性布局
Column() {
Text('Item 1')
Text('Item 2')
Text('Item 3')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.SpaceBetween)
2. 弹性布局
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Text('Left').margin(10)
Text('Center').margin(10)
Text('Right').margin(10)
}
.width('100%')
.padding(10)
3. 网格布局
GridRow() {
GridCol({ span: 6 }) {
Text('Column 1')
}
GridCol({ span: 6 }) {
Text('Column 2')
}
}
四、状态管理
1. 组件状态
@State count: number = 0
Button(`Click Count: ${this.count}`)
.onClick(() => {
this.count++
})
2. 应用状态
@StorageLink('count') storageCount: number = 0
Button(`Storage Count: ${this.storageCount}`)
.onClick(() => {
this.storageCount++
})
五、页面路由
1. 基本路由配置
// pages.json
{
"pages": [
{
"name": "index",
"path": "pages/index/index"
},
{
"name": "detail",
"path": "pages/detail/detail"
}
]
}
2. 页面跳转
// 跳转到详情页
router.push({
url: 'pages/detail/detail',
params: {
id: 123
}
})
// 接收参数
@State id: number = 0
onPageShow() {
const params = router.getParams()
this.id = params['id'] || 0
}
六、网络请求
import http from '@ohos.net.http'
// 创建HTTP请求
let httpRequest = http.createHttp()
// GET请求示例
httpRequest.request(
"https://api.example.com/data",
{
method: 'GET',
header: {
'Content-Type': 'application/json'
}
},
(err, data) => {
if (!err) {
console.log('Response:', data.result)
} else {
console.error('Error:', err)
}
}
)
七、数据持久化
1. 轻量级存储
import preferences from '@ohos.data.preferences'
// 获取Preferences实例
let prefs = await preferences.getPreferences(this.context, 'myprefs')
// 存储数据
await prefs.put('username', 'JohnDoe')
await prefs.flush()
// 读取数据
let username = await prefs.get('username', 'default')
2. 数据库存储
import relationalStore from '@ohos.data.relationalStore'
// 配置数据库
const config = {
name: 'mydb.db',
securityLevel: relationalStore.SecurityLevel.S1
}
// 创建数据库
let rdbStore = await relationalStore.getRdbStore(this.context, config)
// 创建表
const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)'
await rdbStore.executeSql(SQL_CREATE_TABLE)
// 插入数据
const SQL_INSERT = 'INSERT INTO user (name) VALUES (?)'
await rdbStore.executeSql(SQL_INSERT, ['Alice'])
八、设备能力调用
1. 获取设备信息
import deviceInfo from '@ohos.deviceInfo'
let deviceModel = deviceInfo.deviceModel
let osVersion = deviceInfo.osFullName
2. 地理位置
import geolocation from '@ohos.geolocation'
// 获取当前位置
geolocation.getCurrentLocation((err, data) => {
if (err) {
console.error('Error:', err)
return
}
console.log('Location:', data.latitude, data.longitude)
})
九、ArkUI高级特性
1. 自定义组件
@Component
struct CustomButton {
@Prop label: string = 'Button'
@State isPressed: boolean = false
build() {
Button(this.label)
.backgroundColor(this.isPressed ? '#CCCCCC' : '#FFFFFF')
.onClick(() => {
this.isPressed = !this.isPressed
})
}
}
// 使用自定义组件
CustomButton({ label: 'Custom' })
2. 动画效果
@State scale: number = 1
Button('Animate')
.scale({ x: this.scale, y: this.scale })
.onClick(() => {
animateTo({
duration: 1000,
curve: Curve.EaseInOut
}, () => {
this.scale = this.scale === 1 ? 1.5 : 1
})
})
十、性能优化技巧
1. 列表性能优化
LazyForEach(this.dataSource, (item: Item) => {
ListItem() {
Text(item.name)
.fontSize(16)
}
}, (item: Item) => item.id.toString())
2. 图片懒加载
Image($r('app.media.large_image'))
.lazyLoad(true)
.onComplete(() => {
console.log('Image loaded')
})
十一、调试与测试
1. 日志输出
console.debug('Debug message')
console.info('Info message')
console.warn('Warning message')
console.error('Error message')
2. 单元测试
import { describe, it, expect } from '@ohos/hypium'
describe('MathTest', () => {
it('add_test', 0, () => {
let a = 1
let b = 2
expect(a + b).assertEqual(3)
})
})
十二、打包与发布
1. 应用配置
// config.json
{
"app": {
"bundleName": "com.example.myapp",
"vendor": "example",
"version": {
"code": 1,
"name": "1.0.0"
}
}
}
2. 构建命令
# 开发构建
npm run build
# 发布构建
npm run build:release
以上是鸿蒙Ark开发的基础知识概览,涵盖了UI开发、状态管理、网络请求、数据存储等核心内容。随着HarmonyOS的不断发展,ArkUI框架也在持续演进,建议开发者关注官方文档获取最新信息。