在鸿蒙Next(HarmonyOS NEXT)中,Select组件用于创建下拉选择菜单,允许用户从多个选项中选择一个值。以下是基本使用方法:
1. 基本用法
在ArkUI中,使用Select组件并绑定选项数据。
import { Select, SelectOption } from '@kit.ArkUI';
@Entry
@Component
struct SelectExample {
@State selectedIndex: number = 0; // 当前选中项的索引
private options: string[] = ['选项1', '选项2', '选项3']; // 选项数组
build() {
Column() {
// 创建Select组件
Select(this.options.map((item, index) => {
return { value: item, index: index };
}))
.selected(this.selectedIndex) // 绑定当前选中项
.onSelect((index: number) => { // 选择事件回调
this.selectedIndex = index;
console.info(`选中: ${this.options[index]}`);
})
.width(120)
}
.padding(20)
.width('100%')
}
}
2. 关键属性说明
selected:绑定当前选中项的索引(number类型)。
onSelect:选择变化时的回调函数,返回选中项的索引。
- 选项数据:需通过数组提供,每个元素包含
value(显示文本)和index(索引值)。
3. 自定义样式
可通过链式调用修改样式:
Select(...)
.fontSize(16)
.fontColor(Color.Blue)
.backgroundColor('#F5F5F5')
注意事项
- 确保选项索引从0开始且连续。
- 若需动态更新选项,需使用
@State修饰选项数组。
- 鸿蒙Next的API可能随版本更新,建议查阅最新官方文档。
通过以上代码即可实现基础下拉选择功能,适用于设置选择、表单输入等场景。