技术栈
Appgallery connect
开发准备
上一节我们实现了顶部toolbar的地址选择,会员码展示,首页的静态页面就先告一段落,这节我们来实现商品列表item的点击传值、自定义标题栏。
功能分析
1.自定义标题栏
当我们进入二级三级页面的时候,就需要向用户介绍我们当前的页面信息,标题栏很好的实现了这个效果,并且进入的页面级别过多,也要给用户一个可点击的退出按钮。当然了,有些页面是不需要有返回按钮的,这里我们还要兼顾通用性。
2.页面间传值
页面之前的数据传递,是app中比较常见也是比较重要的知识点,这里我们通过点击列表的条目进行数据的传递,然后在详情页进行数据的接收
代码实现
自定义标题栏
import router from '@ohos.router'
@Component
export struct CommonTopBar {
@Prop title: string
@Prop alpha: number
private titleAlignment: TextAlign = TextAlign.Center
private backButton: boolean = true
private onBackClick?: () => void
build() {
Column() {
Blank()
.backgroundColor(Color.Red)
.opacity(this.alpha)
Stack({ alignContent: Alignment.Start }) {
Stack()
.height(50)
.width("100%")
.opacity(this.alpha)
.backgroundColor(Color.Red)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Text(this.title)
.flexGrow(1)
.textAlign(this.titleAlignment)
.fontSize(18)
.fontColor(Color.Black)
.align(Alignment.Center)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.height(50)
.margin({ left: 50, right: 50 })
.alignSelf(ItemAlign.Center)
if (this.backButton) {
Stack() {
Image($r('app.media.ic_back'))
.height(16)
.width(12)
.objectFit(ImageFit.Contain)
.align(Alignment.Center)
}
.onClick(() => {
this.onBackClick?.()
router.back();
})
.height(50)
.width(50)
}
}
.height(50)
.width("100%")
Divider().strokeWidth(0.5).color("#E6E6E6")
}.backgroundColor(Color.White)
.height(51)
}
}
在标题栏中我们使用了一些逻辑判断,并且设置标题是外部传入的,而且还预留了一个事件的回调,这能让我们的标题栏更加的灵活
页面间传值
首先我们需要创建一个商品详情页的页面,然后把我们的自定义标题栏引入进去
import { CommonTopBar } from '../widget/CommonTopBar';
@Entry
@Component
struct ProductDetailsPage {
build() {
Column() {
CommonTopBar({ title: "商品详情", alpha: 0, titleAlignment: TextAlign.Center ,backButton:true})
}
.height('100%')
.width('100%')
}
}
然后在商品流的点击事件里使用router
.onClick(() => {
router.pushUrl({
url: 'pages/component/ProductDetailsPage',
params: item
}, (err) => {
if (err) {
console.error(`Invoke pushUrl failed, code is ${err.code}, message is ${err.message}`);
return;
}
console.info('Invoke pushUrl succeeded.');
});
})
这里我们把整个item的信息都传递过去,方便我们使用
接收
@State receivedParams: HomeProductList = {} as HomeProductList;
aboutToAppear(): void {
let order= router.getParams() as HomeProductList;
console.info('Received params:',order);
}
在页面上我们先展示出来
Text(JSON.stringify(this.receivedParams))
.fontColor(Color.Black)
到这里我们就实现了本节的内容了,下一节我们将要丰富商品详情页的内容