ArkTS 常用 UI 组件的分类

257 阅读3分钟

ArkTS UI 组件分类与使用详解

ArkTS 提供了一套丰富、声明式的 UI 组件,用于构建鸿蒙应用的用户界面。开发者通过组合这些组件来描述 UI 的结构、内容和行为。本文档将常用组件进行分类,并详细介绍其核心作用及基本使用方法。

目录

  1. 布局组件 (Layout)

  2. 基础组件 (Basic)

  3. 容器组件 (Container)

  4. 交互与输入组件 (Interactive & Input)

  5. 通用属性


1. 布局组件 (Layout)

布局组件用于控制子组件的排列方式,是构建 UI 骨架的基础。

Column

  • 作用: 在垂直方向上排列其子组件。

  • 常用属性:

    • space: 子组件之间的垂直间距。
    • alignItems: 子组件在水平方向上的对齐方式 (HorizontalAlign.Start, .Center, .End)。
  • 使用方法:

TypeScript

@Component
struct ColumnExample {
  build() {
    Column({ space: 10 }) {
      Text('项目 1')
      Text('项目 2')
      Text('项目 3')
    }
    .width('100%')
    .padding(10)
    .border({ width: 1, color: Color.Gray })
  }
}

Row

  • 作用: 在水平方向上排列其子组件。

  • 常用属性:

    • space: 子组件之间的水平间距。
    • justifyContent: 子组件在水平方向上的对齐方式 (FlexAlign.Start, .Center, .End, .SpaceBetween)。
    • alignItems: 子组件在垂直方向上的对齐方式 (VerticalAlign.Top, .Center, .Bottom)。
  • 使用方法:

TypeScript

@Component
struct RowExample {
  build() {
    Row({ space: 15 }) {
      Button('按钮 A')
      Button('按钮 B')
    }
    .width('100%')
    .justifyContent(FlexAlign.Center)
  }
}

Stack

  • 作用: 将子组件层叠堆放,后一个组件会覆盖前一个组件。非常适合实现覆盖效果。

  • 常用属性:

    • alignContent: 所有子组件的对齐方式。
  • 使用方法:

TypeScript

@Component
struct StackExample {
  build() {
    Stack({ alignContent: Alignment.BottomEnd }) {
      Image($r('app.media.background_image'))
        .width('100%')
        .height(200)

      Text('图片标题')
        .fontSize(20)
        .fontColor(Color.White)
        .padding(10)
    }
  }
}

Flex

  • 作用: 最灵活的布局方式,可以把它看作是 RowColumn 的超集。

  • 常用属性:

    • direction: 主轴方向 (FlexDirection.Row, .Column)。
    • justifyContent: 主轴对齐方式。
    • alignItems: 交叉轴对齐方式。
    • wrap: 是否换行 (FlexWrap.Wrap)。
  • 使用方法:

TypeScript

@Component
struct FlexExample {
  build() {
    Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap, justifyContent: FlexAlign.SpaceAround }) {
      ForEach(['标签1', '标签2', '标签3', '标签4', '标签5'], (item: string) => {
        Text(item)
          .padding({ top: 5, bottom: 5, left: 10, right: 10 })
          .backgroundColor(Color.Gray)
          .margin(5)
      })
    }
    .width('100%')
  }
}

Grid

详见 容器组件 部分,Grid 既是布局也是容器。

Divider

  • 作用: 用于创建一条分割线,以分隔内容。

  • 常用属性:

    • vertical: 是否为垂直分割线 (默认为 false,水平)。
    • strokeWidth: 线条宽度。
    • color: 线条颜色。
  • 使用方法:

TypeScript

@Component
struct DividerExample {
  build() {
    Column() {
      Text('内容一')
      Divider().strokeWidth(2).color(Color.Red).margin(10)
      Text('内容二')
    }
  }
}

Blank

  • 作用: 创建一个空白占位区域,常用于 RowColumn 中,将其他组件推向两端。

  • 常用属性:

    • color: 空白区域的背景色(用于调试)。
  • 使用方法:

TypeScript

@Component
struct BlankExample {
  build() {
    Row() {
      Text('左侧')
      Blank() // 占据所有可用空间
      Text('右侧')
    }
    .width('100%')
    .height(40)
    .backgroundColor(Color.LightGray)
  }
}

2. 基础组件 (Basic)

基础组件是构成 UI 内容的原子元素。

Text

  • 作用: 显示一段只读文本。
  • 常用属性: fontSize, fontColor, fontWeight, textAlign, maxLines, textOverflow
  • 使用方法:

TypeScript

Text('你好, ArkTS!')
  .fontSize(24)
  .fontWeight(FontWeight.Bold)
  .fontColor(Color.Blue)

Image

  • 作用: 显示图片,支持本地资源、网络图片和 base64 数据。
  • 常用属性: src, width, height, objectFit (ImageFit.Cover, .Contain)。
  • 使用方法:

TypeScript

// 本地资源
Image($r('app.media.logo'))
  .width(100)
  .height(100)

// 网络图片
Image('https://example.com/image.png')
  .width(100)
  .height(100)

ImageAnimator

  • 作用: 播放帧动画。
  • 常用属性: images (图片资源数组), duration (单次播放时长), reverse (是否反向播放), fixedSize (是否固定尺寸)。
  • 使用方法:

TypeScript

ImageAnimator()
  .images([
    { src: $r('app.media.frame1') },
    { src: $r('app.media.frame2') },
    { src: $r('app.media.frame3') }
  ])
  .duration(1500) // 1.5秒
  .width(100)
  .height(100)

Progress

  • 作用: 显示一个进度条。
  • 常用属性: value (当前进度), total (总进度), type (ProgressType.Linear, .Ring, .Scale)。
  • 使用方法:

TypeScript

Progress({ value: 60, total: 100, type: ProgressType.Ring })
  .width(80)
  .color(Color.Green)

Rating

  • 作用: 显示一个评分组件(星级评分)。
  • 常用属性: rating (当前分数), stars (总星星数)。
  • 使用方法:

TypeScript

@State ratingValue: number = 3.5
Rating({ rating: this.ratingValue, stars: 5 })
  .onChange((value: number) => {
    this.ratingValue = value
  })

TextClock

  • 作用: 显示一个实时更新的文本时钟。
  • 常用属性: format (时间格式, e.g., 'HH:mm:ss')。
  • 使用方法:

TypeScript

TextClock({ format: 'yyyy-MM-dd HH:mm:ss' })
  .fontSize(16)

3. 容器组件 (Container)

容器组件用于承载和组织大量或可滚动的内容。

List

  • 作用: 高性能的列表容器,用于显示长列表数据。它只渲染视口内和缓存区内的列表项,实现按需渲染。
  • 子组件: 必须是 ListItem
  • 常用属性: space (列表项间距), divider (分割线)。
  • 使用方法:

TypeScript

@Component
struct ListExample {
  private items: string[] = Array.from({ length: 100 }, (_, i) => `列表项 ${i + 1}`);

  build() {
    List({ space: 10 }) {
      ForEach(this.items, (item: string) => {
        ListItem() {
          Text(item).fontSize(18).width('100%').padding(15)
        }
        .backgroundColor(Color.White)
      })
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.LightGray)
  }
}

Grid

  • 作用: 二维网格布局容器,用于按行和列显示内容。
  • 子组件: 必须是 GridItem
  • 常用属性: columnsTemplate (列宽模板), rowsTemplate (行高模板), columnsGap (列间距), rowsGap (行间距)。
  • 使用方法:

TypeScript

@Component
struct GridExample {
  build() {
    Grid() {
      ForEach(new Array(6).fill(0), (item, index) => {
        GridItem() {
          Text(`${index + 1}`)
            .width('100%')
            .height('100%')
            .backgroundColor(Color.Blue)
            .fontColor(Color.White)
            .textAlign(TextAlign.Center)
            .fontSize(20)
        }
      })
    }
    .columnsTemplate('1fr 1fr 1fr') // 定义三列,每列平分宽度
    .rowsTemplate('100px 100px')   // 定义两行,每行高100px
    .columnsGap(10)
    .rowsGap(10)
    .width('100%')
  }
}

Swiper

  • 作用: 可滑动的容器,用于实现轮播图、引导页等效果。
  • 常用属性: index (当前页索引), autoPlay (自动播放), interval (播放间隔), indicator (是否显示指示器)。
  • 使用方法:

TypeScript

@Component
struct SwiperExample {
  build() {
    Swiper() {
      Image($r('app.media.page1')).backgroundColor(Color.Red)
      Image($r('app.media.page2')).backgroundColor(Color.Green)
      Image($r('app.media.page3')).backgroundColor(Color.Blue)
    }
    .width('100%')
    .height(200)
    .autoPlay(true)
    .indicator(true)
  }
}

Tabs

  • 作用: 创建标签页布局,包含一个 TabBar (标签栏) 和一个 TabContent (内容区)。
  • 常用属性: barPosition (BarPosition.Start.End), index (当前激活的 Tab 索引)。
  • 使用方法:

TypeScript

@Component
struct TabsExample {
  @State currentIndex: number = 0;
  private controller: TabsController = new TabsController();

  build() {
    Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
      TabContent() {
        Column().width('100%').height('100%').backgroundColor(Color.Gray)
      }
      .tabBar('Tab 1') // 设置TabBar文字

      TabContent() {
        Text('这是内容2')
      }
      .tabBar('Tab 2')
    }
    .onChange((index: number) => {
      this.currentIndex = index;
    })
  }
}

Scroll

  • 作用: 通用滚动容器。当内容超出其尺寸时,提供滚动能力。
  • 常用属性: scrollable (ScrollDirection.Vertical, .Horizontal), scrollBar (BarState.On, .Off)。
  • 使用方法:

TypeScript

Scroll() {
  Column() {
    // 放入大量内容
    ForEach(new Array(30).fill(0), (item, index) => {
      Text(`滚动内容 ${index + 1}`).padding(10)
    })
  }
}
.width('100%')
.height(300)
.scrollBar(BarState.Auto)
.backgroundColor(Color.LightGray)

Panel

  • 作用: 可拖拽面板,通常从屏幕底部或侧边滑出。
  • 常用属性: isShown (是否显示), type (PanelType.Minibar, .Foldable), mode (PanelMode.Half, .Full)。
  • 使用方法:

TypeScript

@State isPanelShown: boolean = false
// ... 在 build 方法中 ...
Panel(this.isPanelShown) {
  // 面板内容
  Text('这是面板内容').padding(20)
}
.type(PanelType.Foldable)
.mode(PanelMode.Half)

4. 交互与输入组件 (Interactive & Input)

这些组件用于接收用户的操作和输入。

Button

  • 作用: 触发操作的按钮。
  • 常用属性: type (ButtonType.Capsule, .Circle, .Normal), stateEffect (点击效果)。
  • 核心事件: onClick
  • 使用方法:

TypeScript

Button('点击我', { type: ButtonType.Capsule })
  .width(200)
  .height(40)
  .backgroundColor(Color.Blue)
  .onClick(() => {
    console.log('按钮被点击');
  })

TextInput

  • 作用: 单行文本输入框。
  • 常用属性: placeholder (占位文本), text (绑定的文本内容), type (InputType.Number, .Password, .Email)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

@State myText: string = ''
TextInput({ placeholder: '请输入用户名', text: this.myText })
  .onChange((value: string) => {
    this.myText = value
  })

TextArea

  • 作用: 多行文本输入框。
  • 常用属性: placeholder, text
  • 使用方法:

TypeScript

@State myArticle: string = ''
TextArea({ placeholder: '请输入文章内容', text: this.myArticle })
  .height(150)

Toggle

  • 作用: 开关按钮,用于在两种状态(开/关)之间切换。
  • 常用属性: isOn (是否选中)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

@State isNotificationOn: boolean = true
Toggle({ isOn: this.isNotificationOn })
  .onChange((isOn: boolean) => {
    this.isNotificationOn = isOn
  })

Radio

  • 作用: 单选按钮。在一组 Radio 中,一次只能选择一个。
  • 常用属性: checked (是否选中), group (所属分组名)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

@State selectedFruit: string = 'Apple'
Column() {
  Radio({ value: 'Apple', group: 'fruit' })
    .checked(this.selectedFruit === 'Apple')
    .onChange((isChecked: boolean) => { if(isChecked) this.selectedFruit = 'Apple' })
  Radio({ value: 'Banana', group: 'fruit' })
    .checked(this.selectedFruit === 'Banana')
    .onChange((isChecked: boolean) => { if(isChecked) this.selectedFruit = 'Banana' })
}

Checkbox

  • 作用: 复选框,用于多项选择。
  • 常用属性: select (是否选中), name (分组名)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

@State isAgreed: boolean = false
Checkbox({ name: 'agreement', group: 'user' })
  .select(this.isAgreed)
  .onChange((value: boolean) => {
    this.isAgreed = value
  })

Slider

  • 作用: 滑动条,用于在连续或间断的范围内选择一个值。
  • 常用属性: value (当前值), min, max, step (步长)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

@State volume: number = 50
Slider({ value: this.volume, min: 0, max: 100, step: 1, style: SliderStyle.OutSet })
  .onChange((value: number, mode: SliderChangeMode) => {
    this.volume = value
  })

DatePicker / TimePicker

  • 作用: 提供标准的日期和时间选择界面。
  • 常用属性: selected (选中的日期/时间)。
  • 核心事件: onChange
  • 使用方法:

TypeScript

DatePicker({
  start: new Date('2020-01-01'),
  end: new Date('2030-12-31'),
  selected: new Date()
})
.onChange((value: Date) => {
  console.log('选择的日期: ' + value.toLocaleDateString())
})

TimePicker()
.onChange((value: Time) => {
  console.log(`选择的时间: ${value.hour}:${value.minute}`)
})

5. 通用属性

大多数组件都支持一些通用属性,用于设置它们的公共样式和行为。

  • 尺寸: .width(), .height(), .constraintSize()
  • 内外边距: .padding(), .margin()
  • 背景: .backgroundColor(), .backgroundBlur(), .backgroundImage()
  • 边框: .border(), .borderRadius()
  • 事件: .onClick(), .onTouch(), .onAppear(), .onDisAppear()
  • 可见性: .visibility() (Visibility.Visible, .Hidden, .None)
  • 禁用: .enabled(false)
  • 透明度: .opacity()