HarmonyOS 鸿蒙Next我想写个能复用的样式
HarmonyOS 鸿蒙Next我想写个能复用的样式
【设备信息】Mate60
【API版本】Api12
【DevEco Studio版本】5.0.3.814
【问题描述】
我有两个text里的样式完全一样,我抽出来写@style,但是它说fontsize不可以写在外面,那怎么写通用样式?顺便可以发个这种demo给我看看吗
5 回复
可以通过attributeModifier属性动态的设置组件,通过自定义class继承对应基础组件的Modifier,在class中设置复用的属性
// xxx.ets
class MyButtonModifier implements AttributeModifier<TextAttribute> {
isDark: boolean = false
applyNormalAttribute(instance: TextAttribute): void {
if (this.isDark) {
instance.backgroundColor(Color.Black)
} else {
instance.backgroundColor(Color.Red)
}
instance.fontSize(55)
}
}
@Entry
@Component
struct attributeDemo {
@State modifier: MyButtonModifier = new MyButtonModifier()
build() {
Row() {
Column() {
Text("Button")
.attributeModifier(this.modifier)
.onClick(() => {
this.modifier.isDark = !this.modifier.isDark
})
Text("呵呵")
.attributeModifier(this.modifier)
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS 鸿蒙Next我想写个能复用的样式的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
我的办法比较笨,我自己封装了一下text
在HarmonyOS鸿蒙Next中,可以通过定义全局样式来实现样式的复用。使用@Styles
装饰器可以创建可复用的样式,应用于多个组件。例如:
@Styles function commonStyle() {
.width(100)
.height(100)
.backgroundColor(Color.Red)
}
@Entry
@Component
struct MyComponent {
build() {
Column() {
Text('Text 1')
.commonStyle()
Text('Text 2')
.commonStyle()
}
}
}
在上述代码中,commonStyle
定义了一个样式,并应用于两个Text
组件。通过这种方式,可以在多个组件中复用相同的样式。