📚 鸿蒙入门专栏 · 第 7 篇 / 共 10 篇
上一篇:布局系统:Column/Row/Stack/Flex | 下一篇:页面跳转:router 与 Navigation
常用组件:Text/Image/Button/List 实战拼页面
目录
[常用组件:Text/Image/Button/List 实战拼页面](#常用组件:Text/Image/Button/List 实战拼页面)
前两篇打了地基,这篇开始盖房子:把常用组件过一遍,并亲手拼出一个完整的「我的」页面。

一、四大高频组件速览
// Text:文字
Text("鸿蒙入门")
.fontSize(18) // 字号
.fontColor('#0A59F7') // 颜色
.fontWeight(FontWeight.Bold) // 加粗
.maxLines(1) // 最大行数
.textOverflow({ overflow: TextOverflow.Ellipsis }) // 超出省略号
// Image:图片(resources/base/media 下放图片)
Image($r('app.media.avatar')) // 引用资源图
.width(60).height(60)
.borderRadius(30) // 圆形头像
.objectFit(ImageFit.Cover) // 裁剪填充
// Button:按钮
Button("提交")
.width('90%').height(44)
.backgroundColor('#0A59F7')
.onClick(() => { console.log("被点了") })
// TextInput:输入框
TextInput({ placeholder: "请输入用户名" })
.height(44)
.onChange((v: string) => { console.log(v) })
二、List:可滚动列表
内容超过一屏必须用 List,它会自动回收不可见的元素,性能好:
@Entry
@Component
struct DemoList {
@State items: string[] = ["订单", "收藏", "优惠券", "地址", "客服", "设置"]
build() {
List({ space: 10 }) {
ForEach(this.items, (item: string) => {
ListItem() {
Row({ space: 10 }) {
Text("📄").fontSize(20)
Text(item).fontSize(15)
Blank()
Text(">").fontColor('#ccc')
}
.padding(14)
.backgroundColor(Color.White).borderRadius(10)
}
}, (item: string) => item) // 键值生成函数
}
.padding(12)
.backgroundColor('#F5F7FA')
.width('100%').height('100%')
}
}
⚠️ ForEach 第三个参数(键值函数)别省略,列表数据更新出 bug 十有八九是它的问题。
三、综合实战:完整的「我的」页面
@Entry
@Component
struct MinePage {
@State name: string = "张小明"
build() {
Column() {
// 顶部个人信息卡
Row({ space: 14 }) {
Image($r('app.media.avatar')).width(64).height(64).borderRadius(32)
Column({ space: 4 }) {
Text(this.name).fontSize(20).fontWeight(FontWeight.Bold)
Text("鸿蒙学习者 LV.1").fontSize(13).fontColor('#999')
}
.alignItems(HorizontalAlign.Start)
.layoutWeight(1)
Text("编辑资料 >").fontSize(13).fontColor('#0A59F7')
}
.width('100%').padding(20)
.linearGradient({
angle: 135, colors: [['#0A59F7', 0], ['#4F8CFF', 1]]
})
// 菜单列表
List({ space: 10 }) {
ForEach(["我的订单", "我的收藏", "设置"], (item: string) => {
ListItem() {
Row() {
Text(item).fontSize(15)
Blank()
Text(">").fontColor('#ccc')
}.padding(16).backgroundColor(Color.White)
}
}, (item: string) => item)
}
.layoutWeight(1)
Button("退出登录")
.width('90%').height(44)
.backgroundColor(Color.White)
.fontColor('#D93026')
.margin({ bottom: 20 })
}
.width('100%').height('100%').backgroundColor('#F5F7FA')
}
}
💡 把头像图随便一张 png 拖进 resources/base/media 目录并命名 avatar,就能跑。跑通后试试改成你自己的名字------改完这篇,你已经能独立做静态页面了。
四、下一篇预告
页面只能显示可不行,点「编辑资料」应该跳转到新页面。下一篇:页面跳转与路由。
如果这篇对你有帮助,点赞 + 收藏 + 关注 三连支持一下,后续教程更新不迷路。
有报错解决不了?评论区贴出报错信息 + 代码,看到都会回。