鸿蒙动态属性
attributeModifier
官网的介绍是:动态设置组件的属性,支持开发者在属性设置时使用if/else语法,且根据需要使用多态样式设置属性。
一下是使用动态属性实现的一个小案例通过官网的例子改造而来
第一步首选需要去写一个我们自己的动态属性类它是继承CommonModifier来的
里面就是通过isScale这个变量来控制用哪里的属性,它和直接在属性里面用三元运算来控制属性有个区别就是动态属性他需要这个属性就加上没有就不要,而三元运算符必须要有这个属性。
class MyModifier extends CommonModifier {
// 是否放大缩小
public isScale: boolean = false;
/**
* 定义组件普通状态时的样式
* @param instance: ListItem属性
*/
applyNormalAttribute(instance: ListItemAttribute): void {
if (this.isScale) {
instance.width(150)
instance.height(150)
instance.rotate({
x: 0,
y: 0,
z: 1,
centerX: '50%',
centerY: '50%',
angle: 300
}) // 组件以矢量(0,0,1)为旋转轴,绕中心点顺时针旋转300度
} else {
instance.width(50)
instance.height(50)
instance.rotate({
x: 0,
y: 0,
z: 1,
centerX: '50%',
centerY: '50%',
angle: 100
}) // 组件以矢量(0,0,1)为旋转轴,绕中心点顺时针旋转300度
}
}
}
第二步去new我的类 可以给一些属性在上面
@State myModifier: CommonModifier = new MyModifier().width(100).height(100).margin(10)
第三步 用attributeModifier把类绑在我们组件上
Image($r("app.media.startIcon")).attributeModifier(this.modifier)
第四步 改变我们在类里面定义的变量就可以了 为了好看可以使用animateTo加点动画过渡
.onClick(() => {
console.log("Modifier", "onClick")
this.index++;
if (this.index % 2 === 1) {
console.log("Modifier", "setGroup1")
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
(this.myModifier as MyModifier).isScale = true;
})
} else {
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
(this.myModifier as MyModifier).isScale = false;
})
}
})
以上就是使用动态属性实现的一个小demo
import { CommonModifier } from '@kit.ArkUI';
class MyModifier extends CommonModifier {
// 是否放大缩小
public isScale: boolean = false;
/**
* 定义组件普通状态时的样式
* @param instance: ListItem属性
*/
applyNormalAttribute(instance: ListItemAttribute): void {
if (this.isScale) {
instance.width(150)
instance.height(150)
instance.rotate({
x: 0,
y: 0,
z: 1,
centerX: '50%',
centerY: '50%',
angle: 300
}) // 组件以矢量(0,0,1)为旋转轴,绕中心点顺时针旋转300度
} else {
instance.width(50)
instance.height(50)
// instance.rotate({
// x: 0,
// y: 0,
// z: 1,
// centerX: '50%',
// centerY: '50%',
// angle: 100
// }) // 组件以矢量(0,0,1)为旋转轴,绕中心点顺时针旋转300度
}
}
}
// 跳转页面入口函数
@Builder
export function pageOneBuild() {
Index()
}
@Component
struct MyImage1 {
@Link modifier: CommonModifier
build() {
Image($r("app.media.startIcon")).attributeModifier(this.modifier)
}
}
@Entry
@Component
struct Index {
@State myModifier: CommonModifier = new MyModifier().width(100).height(100).margin(10)
index: number = 0;
build() {
NavDestination() {
Button($r("app.string.EntryAbility_label"))
.margin(10)
.onClick(() => {
console.log("Modifier", "onClick")
this.index++;
if (this.index % 2 === 1) {
console.log("Modifier", "setGroup1")
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
(this.myModifier as MyModifier).isScale = true;
})
} else {
animateTo({ curve: Curve.Friction, duration: 300 }, () => {
(this.myModifier as MyModifier).isScale = false;
})
}
})
MyImage1({ modifier: this.myModifier })
}
.width('100%')
}
}