想把某个属性单独写出来通用怎么弄 HarmonyOS 鸿蒙Next
想把某个属性单独写出来通用怎么弄 HarmonyOS 鸿蒙Next
.shadow({ radius: 1, type: ShadowType.COLOR, color: ‘#0FB3B3B3’, offsetY: 3, fill: true })
更多关于想把某个属性单独写出来通用怎么弄 HarmonyOS 鸿蒙Next的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
可以使用attributeModifier动态属性设置,
1.commonStyles.ets
export class MyButtonModifier implements AttributeModifier<ButtonAttribute> {
isDark: boolean = false
applyNormalAttribute(instance: ButtonAttribute): void {
if (this.isDark) {
instance.backgroundColor(Color.Black)
} else {
instance.backgroundColor(Color.Red)
instance.shadow({
radius: 1,
type: ShadowType.COLOR,
color: Color.Green,
offsetY: 3,
fill: true
})
}
}
}
2.index.ets
import { MyButtonModifier } from './commonStyles'
@Entry
@Component
struct attributeDemo {
@State modifier: MyButtonModifier = new MyButtonModifier()
build() {
Row() {
Column() {
Button("Button")
.attributeModifier(this.modifier)
.onClick(() => {
this.modifier.isDark = !this.modifier.isDark
})
}
.width('100%')
}
.height('100%')
}
}
更多关于想把某个属性单独写出来通用怎么弄 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,若要将某个属性单独写出来通用,可以使用[@State](/user/State)
、[@Prop](/user/Prop)
或[@Link](/user/Link)
装饰器来实现属性的共享和复用。
-
[@State](/user/State)
:用于组件内部的状态管理,属性变化会触发UI更新。例如:[@State](/user/State) message: string = 'Hello';
-
[@Prop](/user/Prop)
:用于父子组件之间的单向数据传递,父组件的属性变化会同步到子组件。例如:[@Prop](/user/Prop) message: string;
-
[@Link](/user/Link)
:用于父子组件之间的双向数据绑定,父子组件的属性变化会相互同步。例如:[@Link](/user/Link) message: string;
通过这些装饰器,可以将属性抽象出来,实现跨组件的共享和复用。