@Styles
说明
注意
@Styles 只能写
通用属性
(例如宽高)和通用事件
(onClicke)@Styles 可以改变组件的状态
@Styles 不能传递任何参数
@Styles 分成局部和全局
局部
ts
@Entry
@Component
struct Index {
@State message: string = "今天开始改变"
// 局部样式
@Styles
commonStyle(){
.width(200)
.height(200)
.backgroundColor(Color.Blue)
.onClick(() => {
this.message = "测试改变了没有"
})
}
build() {
Column() {
Text(this.message)
.commonStyle()
.fontColor(Color.Yellow)
}
}
}
全局
- 全局后面都接的是 function
ts
@Styles
function normalize() {
.width(300)
.height(300)
.backgroundColor(Color.Red)
.onClick(() => {
console.log("测试改变了没有")
})
}
@Entry
@Component
struct Index {
@State message: string = "今天开始改变"
build() {
Column() {
Text(this.message)
.normalize()
.fontColor(Color.Yellow)
}
}
}
局部和全局都有
他会优先找局部
如果外边写了其他属性比如
fontColor
他会优先找属性属性>局部>全局
ts
@Styles
function normalize() {
.width(300)
.height(300)
.backgroundColor(Color.Red)
.onClick(() => {
console.log("测试改变了没有")
})
}
@Entry
@Component
struct Index {
@State message: string = "今天开始改变"
// 局部样式
@Styles
commonStyle(){
.width(200)
.height(200)
.backgroundColor(Color.Blue)
.onClick(() => {
this.message = "测试改变了没有"
})
}
build() {
Column() {
Text(this.message)
.normalize()
.commonStyle()
.fontColor(Color.Yellow)
}
}
}
通过文件引入(重点)
新建一个文件
- utils/setAttribute.ts
注意
1.如果是其他组件比如 Button 就换成 ButtonAttribute
ts
export class MyTextModifier implements AttributeModifier<TextAttribute> {
applyNormalAttribute(instance: TextAttribute): void {
instance
.fontColor(Color.Red)
.width(300)
.height(100)
.backgroundColor(Color.Black)
.textAlign(TextAlign.Center)
.onClick(() => {
console.log("点击了");
});
}
}
export class MyButtonModifier implements AttributeModifier<ButtonAttribute> {
applyNormalAttribute(instance: ButtonAttribute): void {
instance
.fontColor(Color.Red)
.width(300)
.height(100)
.backgroundColor(Color.Black)
.onClick(() => {
console.log("点击了");
});
}
}
- 页面里面使用的时候
注意
引入后 必须 new 一个实例
attributeModifier 里面必须传实例
ts
import { MyButtonModifier, MyTextModifier } from '../utils/setAttribute'
@Entry
@Component
struct Index {
@State message: string = "今天开始改变"
@State Textmodifier: MyTextModifier = new MyTextModifier()
@State Buttonmodifier: MyButtonModifier = new MyButtonModifier()
build() {
Column() {
Text(this.message)
.attributeModifier(this.Textmodifier).margin({
bottom: 30
})
Button("点击了我")
.attributeModifier(this.Buttonmodifier)
}
}
}