@Extend,@styles和@Builder 的区别

312 阅读1分钟

在鸿蒙开发当中,随着页面布局的复杂程度提高,会遇到许重复的代码,如果将它们进行封装复用会大大提高我们的编码效率,同时提高了代码的可读性。

@Extend可以扩展组件的样式、事件,实现复用效果

@Extend 它强调对某一个组件进行封装,而且只能在全局进行定义,并且传递参数。 @Extend 的调用只对它抽取的组件有用,通过点类型进行复用。

@Extend(Text)
function text(bgcolor?: ResourceColor) {
  .fontSize(20)
  .fontColor(bgcolor)
  .fontWeight(700)
}

@Entry
@Component
struct Index {
  build() {
    Column() {
      Text('内容')
        .text()
      Text('文本')
        .text(Color.Green)

    }
    .width('100%')

  }
}

image.png

@Styles 可以抽取 通用的事件和属性。

不同于@Extend 用来给某个组件扩展,@Styles 可以抽取 通用的事件和属性,但是它不可以传递参数。它也可以分为全局定义和局部定义,它也是通过点类型进行复用的

//全局定义
@Styles
function attribute() {
  .width(100)
  .height(100)
  .backgroundColor(Color.Orange)
}

@Entry
@Component
struct Index {
  //局部定义
  @Styles
  signal(){
    .width(100)
    .height(100)
    .onClick(() => {
      AlertDialog.show({
        message: "aaa",
      })
    })
  }

  build() {
    Column() {
      Text('内容')
        .attribute()
      Button('点击')
        .signal()
    }
    .width('100%')

  }
}

image.png

@Builder:自定义构建函数。连结构也需要抽取就可以使用。

  1. 组件内 自定义构建函数 需要通过 this 复用。
  2. 全局 自定义构建函数 没有上述特点
//全局定义
@Builder
function aaa() {
  Column() {
    Text('全局')
      .width(100)
      .fontSize(30)
  }
  .backgroundColor(Color.Orange)
  .onClick(() => {
    console.log('全局')
  })
}

@Entry
@Component
struct Index {
  //局部定义
  @Builder
  room() {
    Row() {
      Text('局部')
      Text('定义')
    }
    .backgroundColor(Color.Brown)
    .onClick(() => {
      console.log('xxxxx')
    })
  }

  build() {
    Column({ space: 20 }) {
      aaa()
      this.room()
    }
    .width('100%')

  }
}

image.png

image.png