HarmonyOS 鸿蒙Next ForEach创建的控件 在onclick事件里面如何区分控件
HarmonyOS 鸿蒙Next ForEach创建的控件 在onclick事件里面如何区分控件
[@Entry](/user/Entry)
[@Component](/user/Component)
struct ForEachPage {
[@State](/user/State) message: string = 'Hello World';
[@State](/user/State) arr: number[] = [ 1, 2, 3, 4, 5]
build() {
RelativeContainer() {
List(){
ForEach(this.arr,(item:number,index:number)=>{
ListItem(){Row(){Text('文本'+item)}.justifyContent(FlexAlign.Center).width('100%').backgroundColor(0xFFFFFF).height(100)}
.onClick(()=>{
// if(index == 0){
// console.log('1111111111111111111111')
// }else if(index == 1){
// console.log('2222222222222222222222')
// }else if(index == 2){
// console.log('3333333333333333333333')
// }else if(index == 3){
// console.log('4444444444444444444444')
// }else if(index == 4){
// console.log('5555555555555555555555')
// }
switch (index){
case 0:
console.log('1111111111111111111111'); break;
case 1:
console.log('2222222222222222222222'); break;
case 2:
console.log('3333333333333333333333'); break;
case 3:
console.log('4444444444444444444444'); break;
case 4:
console.log('5555555555555555555555'); break;
}
})
},(item:number)=>JSON.stringify(item))
}.divider({strokeWidth:2,color:'#F1F3F5'}).height('90%')
}
.height('100%')
.width('100%')
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
更多关于HarmonyOS 鸿蒙Next ForEach创建的控件 在onclick事件里面如何区分控件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
[@Entry](/user/Entry)
[@Component](/user/Component)
struct Index {
[@State](/user/State) message: string = 'Hello World';
buttons: string[] = ["button1", "button2", "button3", "button4", "button5"];
clickIndex: number = -1;
build() {
Column() {
Text(this.message)
ForEach(this.buttons, (text: string, index: number) => {
Button(text)
.onClick(() => {
this.handleClick(index);
})
})
}
.height(‘100%’)
.width(‘100%’)
}
handleClick(index: number) {
if (index === 0) {
this.message = ‘click button1’;
} else if (index === 1) {
this.message = ‘click button2’;
} else if (index === 2) {
this.message = ‘click button3’;
} else if (index === 3) {
this.message = ‘click button4’;
} else if (index === 4) {
this.message = ‘click button5’;
}
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>