
在上一篇博客 【OpenHarmony】OpenHarmony 开发基础 ② ( DevEco Studio 常用工具 | 参考文档 | 预览器 | 检查器 | 项目文件结构 | Index.ets 首界面 ) 中 , 分析了部分 index.ets 代码 的内容 ,
系统默认生成的 index.ets 代码如下 :
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}下面继续分析上述代码的内容 , 进行基础代码分析 ;
@State message: string = 'Hello World'; 代码分析 :
message: string 是一个变量 ;
@State 注解用于管理页面级变量的状态 , 并且与自定义组件的渲染紧密相关 ;
为该变量设置 @State 注解 , 当 @State 装饰的变量 数据发生变化时 , 会触发所在组件的 build 方法重新渲染 UI 组件 , 从而实现状态与UI的实时绑定更新 ;
在 OpenHarmony 中 , Row 布局组件 就是一个水平的 线性布局 , 该布局中的 组件元素 在水平方向上排列 , 常用属性如下 :
在下面的 build(){} 中添加 Row 组件 , 然后在 Row 组件中再添加了 Column 组件 ;
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('50%')
}
.height('100%')
}Column 组件 垂直方向 默认 在 Row 中 居中对齐 , 水平方向 默认在 Row 中左对齐 ;

Row 组件代码示例 :
@Entry
@Component
struct Example {
build() {
Row({ space: 10 }) { // 设置子组件间距为10
Text('Text1')
.fontSize(20)
.backgroundColor(Color.Green)
Text('Text2')
.fontSize(20)
.backgroundColor(Color.Yellow)
Text('Text3')
.fontSize(20)
.backgroundColor(Color.Gray)
}
.width('80%') // 设置 Row 的宽度
.height('30') // 设置 Row 的高度
.backgroundColor(Color.Pink)
}
}预览器显示效果 : Row 组件宽度占整体宽度的 80% , 高度是 30 vp 视窗像素 ;


在上面涉及到很多设置长度属性的地方 , 如 :
space: 10 设置 Row 布局中的 子组件 之间的 水平间距 ;fontSize(20) 设置 Text 组件 的 字体大小 ;width('80%') 设置 组件宽度 ;height('30') 设置 组件高度 ;OpenHarmony 的 Length 属性值 用于设置组件的尺寸相关属性 , 如 : 宽度 / 高度 / 内边距 / 外边距 等 , 这个属性值可以是 :
OpenHarmony 的 Column 组件 是 垂直线性布局 , 布局中的子组件 沿垂直方向进行排列 , , 常用属性如下 :
代码示例 :
@Entry
@Component
struct Example {
build() {
Column({ space: 20 }) { // 设置子组件间距为10
Text('Text1')
.fontSize(20)
.backgroundColor(Color.Green)
Text('Text2')
.fontSize(20)
.backgroundColor(Color.Yellow)
Text('Text3')
.fontSize(20)
.backgroundColor(Color.Gray)
}
.width('50%') // 设置 Row 的宽度
.height('50%') // 设置 Row 的高度
.backgroundColor(Color.Pink)
.alignItems(HorizontalAlign.Center) // 水平居中
.justifyContent(FlexAlign.Center) // 垂直居中
}
}预览器效果 :

