@Extend组件扩展
在鸿蒙中相同的样式,功能组件可以利用@Extend进行复用
//组件扩展 @Extend(组件命) function 函数名(参数,参数...){}
@Extend(Text)
function textExtend(color: string, size: number) {
.fontColor(color)
.fontSize(size)
}
@Entry
@Component
struct Index {
@Builder
build() {
Column() {
Row() {
Text('小华')
.textExtend('#ff12c5cb', 20)//调用
.fontSize(33) //覆盖
Text('小华2')
.textExtend('#ffc507db', 16)
}
.width('100%')
.height(55)
}
.height('100%')
.width('100%')
}
}
注意:
① 扩展的组件和使用的组件同名,比如 @Extend(Text) ,那么后续通过 Text 才可以点出该扩展
② function 的名字不能与组件本身拥有的属性同名,自身属性优先级更高
例如:Text组件上本身自带有一个fontStyle属性,我们就不能再@Extend(Text) function fontStyle()一个同名方法了
③ 只能在当前组件有用,不能跨组件使用
@Styles通用样式的复用
不同于@Extend 用来给某个组件扩展,@Styles 可以抽取 通用的事件和属性供所有组件使用
//全局基础样式扩展 数据只能写死 无法传参 没有this @styles() function 函数名(){}
@Styles
function style() {
.width(100)
.backgroundColor(Color.Brown)
.height(25)
.onClick(() => {
AlertDialog.show({ message: 'kkk' })
})
}
@Entry
@Component
struct Index {
@State bag: string = '#fff60623'
//局部基础样式扩展 无法传参 存在this @styles() 函数名(){}
@Styles
style1(){
.width(100)
.height(25)
.backgroundColor(this.bag)
.onClick(() => {
this.bag = '#ff10d284'
})
}
@Builder
build() {
Column({ space: 10 }) {
Text('小华')
.style()//全局
.style1() //局部
Button('点击确认')
// .style()//全局
.style1() //局部
}
.height('100%')
.width('100%')
.backgroundColor(Color.Orange)
}
}
注意:
- @Styles 不支持传递参数
- 可以继续添加样式覆盖 @Styles 中定义的内容
- 组件内部写法,可以通过 this 访问组件属性
@Extend、@Styles、@Builder 对比
tabs组件
@Entry
@Component
struct Index {
@State index: number = 0
//要更改默认样式时需要自定义tabBar
@Builder
Tbaritem(name: string, i: number) {
Column({ space: 3 }) {
Image($r('app.media.background'))
.width(30)//利用传入的页签索引实现高亮图标切换
.fillColor(i === this.index ? Color.Red : '')
Text(name)
.fontColor(i === this.index ? Color.Red : '')
}
.height('100%')
}
build() {
Column() {
//组件
Tabs() {
ForEach(['首页', '我的', '首页', '我的', '首页', '我的', '首页', '我的', '首页', '我的', '首页', '我的', '首页',
'我的'],
(item: string, index: number) => {
//主体内容
TabContent() {
Text('我的内容' + index)
}
.height('80%')
//导航
.tabBar(this.Tbaritem(item, index))
})
}
//导航栏滚动
.barMode(BarMode.Scrollable)
//导航栏位置是水平还是垂直
.vertical(false)
//导航栏位置是开头还是结尾
.barPosition(BarPosition.End)
//内容切换动画时间
.animationDuration(0)
//允许内容滑动
.scrollable(true)
//页面切换后触发事件,animationDuration将影响触发时间
.onChange((Index) => {
this.index = Index
})
//点击页签触发事件
.onTabBarClick((Index) => {
this.index = Index
})
}
.width('100%')
.height('100%')
}
}