基础控件、布局和自定义视图

数据由AI生成。

一、基础控件介绍

1. 文本类控件

  • Text:显示文本

    Text('Hello World')
      .fontSize(20)       // 字体大小
      .fontColor('#000')  // 字体颜色
      .fontWeight(500)    // 字体粗细
    
  • TextInput:输入框

    TextInput({ placeholder: '请输入' })
      .type(InputType.Normal)  // 输入类型
      .maxLength(20)           // 最大长度
    

2. 按钮类控件

  • Button:按钮

    Button('点击我', { type: ButtonType.Normal })
      .width(100)
      .height(40)
      .onClick(() => {
        console.log('按钮被点击')
      })
    

3. 图片类控件

  • Image:显示图片

    Image($r('app.media.icon'))
      .width(100)
      .height(100)
      .objectFit(ImageFit.Contain)  // 图片填充方式
    

二、常用布局方式

1. 线性布局

  • Row:水平排列

    Row() {
      Text('左').fontSize(20)
      Text('右').fontSize(20)
    }
    .justifyContent(FlexAlign.SpaceBetween)  // 对齐方式
    
  • Column:垂直排列

    Column() {
      Text('上').fontSize(20)
      Text('下').fontSize(20)
    }
    .alignItems(HorizontalAlign.Center)  // 子项对齐
    

2. 弹性布局

  • Flex:灵活布局

    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
      Text('项目1').flexGrow(1)
      Text('项目2').flexGrow(2)
    }
    

3. 层叠布局

  • Stack:元素叠加

    Stack() {
      Image($r('app.media.bg'))
      Text('水印').fontSize(12)
    }
    

三、自定义控件开发

1. 创建自定义组件

@Component
struct MyCustomComponent {
  // 定义可接收的参数
  @State message: string = '默认文本'

  build() {
    Column() {
      Text(this.message)
        .fontSize(20)
      Button('改变文本')
        .onClick(() => {
          this.message = '新文本'
        })
    }
  }
}

2. 暴露组件属性方法

@Component
export struct MyButton {
  // 暴露可配置属性
  @Prop label: string = '按钮'
  // 暴露事件
  private onClick: () => void = () => {}

  build() {
    Button(this.label)
      .onClick(() => {
        this.onClick()
      })
  }

  // 暴露方法
  public setOnClick(callback: () => void) {
    this.onClick = callback
  }
}

3. 使用自定义组件

@Entry
@Component
struct Index {
  build() {
    Column() {
      // 使用自定义组件
      MyCustomComponent({ message: '初始文本' })
      
      MyButton({ label: '自定义按钮' })
        .setOnClick(() => {
          console.log('自定义按钮被点击')
        })
    }
  }
}

四、实用小技巧

  • 样式复用:使用@Styles装饰器

@Styles function commonStyle() {
  .width(100)
  .height(40)
  .backgroundColor('#f0f0f0')
}

// 使用
Button('样式按钮').commonStyle()
  • 状态管理:使用@State, @Prop, @Link

@Component
struct ParentComponent {
  @State count: number = 0

  build() {
    Column() {
      Text(`计数: ${this.count}`)
      ChildComponent({ count: $count })  // 双向绑定
    }
  }
}

@Component
struct ChildComponent {
  @Link count: number

  build() {
    Button('增加')
      .onClick(() => {
        this.count++
      })
  }
}
  • 列表渲染:使用ForEach

@Entry
@Component
struct ListExample {
  @State arr: string[] = ['苹果', '香蕉', '橙子']

  build() {
    List() {
      ForEach(this.arr, (item: string) => {
        ListItem() {
          Text(item).fontSize(20)
        }
      })
    }
  }
}