定义自定义组件
有时需要在不同的页面写一些相同或者类似的组件代码,如果可以定义为一个组件来使用的话,那会对开发来说方便不少。
语法:
// 定义自定义组件
@Component
struct Header{
private title :string
build(){
Row(){
Image($r('app.media.back'))
.width(30)
Text(this.title)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Blank() // 插入空白组件
Image($r('app.media.refresh'))
.width(30)
}
.width('100%')
.height(50)
}
}
// ...
// 使用时
Header({title:'Hello World'})
将所有的组件添加到一个文件夹中
import {Header} from '../components/herder'
全局自定义构建函数
// 全局自定义构建函数
@Builder function ItemCard(item:Item){
Row(){
Column(){
Text(item.name)
Text(item.price)
}
.alignItems(HorizontalAlign.Start) // 左对齐
.width(300)
}
}
设置一个卡片生成函数,之后在ForEach循环函数中调用即可,将冗长的代码进行封装。
ForEach(this.item,(item:Item)=>{
ItemCard(item) // 列表卡片自定义函数
})
局部自定义构建函数
// 局部自定义构建函数
@Builder ItemCard(item:Item){ // 不用写fuction了
Row(){
Column(){
Text(item.name)
Text(item.price)
}
.alignItems(HorizontalAlign.Start) // 左对齐
.width(300)
}
}
整体代码
import router from '@ohos.router'
import {Header} from '../components/herder'
// 声明一个内部类Item
class Item{
name:string
price:string
discount:number
// 构造函数
constructor(name:string,price:string,discount:number = 0) {
this.name = name
this.price = price
this.discount = discount
}
}
/*
// 全局自定义构建函数
@Builder function ItemCard(item:Item){
Row(){
Column(){
Text(item.name)
Text(item.price)
}
.alignItems(HorizontalAlign.Start) // 左对齐
.width(300)
}
}
*/
@Entry
@Component
struct Index {
@State message1: string = 'Harmony'
@State message2: string = '遥遥领先!'
@State imageWidth : number = 200
private item:Array- = [ // 创建对象
new Item('华为','1000$'),
new Item('菠萝','2000$'),
new Item('小米','3000$'),
new Item('荣耀','4000$'),
new Item('聯想','5000$'),
new Item('Vivo','6000$'),
new Item('苹果','7000$')
]
build() {
Row() {
Column() {
Header({title:'Hello World'})
Image($r('app.media.image'))
.width(this.imageWidth)
.height(200)
.borderRadius(20)
ForEach(this.item,(item:Item)=>{
this.ItemCard(item) // 列表卡片自定义函数 使用this就不会报错了
})
}
.justifyContent(FlexAlign.Start)
.width('100%')
.height('100%')
}
.height('100%')
}
// 局部自定义构建函数
@Builder ItemCard(item:Item){ // 不用写fuction了
Row(){
Column(){
Text(item.name)
Text(item.price)
}
.alignItems(HorizontalAlign.Start) // 左对齐
.width(300)
}
}
}
设置全局公共样式封装函数
// 全局公共样式
@Styles function fillScreen() {
.width('100%')
.height('100%')
}
// ......
Row(){
// ...
}
.fillScreen() // 设置全局样式
如果属性不是公共使用的属性,而是文字的字体大小等属性怎么办?
设置继承封装样式
@Extend(Text)function priceText(){
.fontWeight(FontWeight.Bold)
.fontSize(20)