list里面button的image点击如何修改图片啊? HarmonyOS 鸿蒙Next
list里面button的image点击如何修改图片啊? HarmonyOS 鸿蒙Next
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($rawfile('ich_collect_n_24x24.png')).width(18).height(18)
}
.onClick(() => {
//这里button点击怎么才能修改上面的图片啊。。。
})
尝试一下此Demo
@ObservedV2 class ImageModel { @Trace icon: Resource
constructor(icon: Resource) { this.icon = icon } }
@Entry @Component struct ListDemo { private arr: ImageModel[] = [new ImageModel($rawfile(‘test1.png’)), new ImageModel($rawfile(‘test2.png’)), new ImageModel($rawfile(‘test3.png’))]
build() { Column { List({ space: 20, initialIndex: 0 }) { ForEach(this.arr, (item: ImageModel, index: number) => { ListItem() { Button({ type: ButtonType.Circle, stateEffect: true }) { Image(item.icon).width(50).height(50) } }.onClick(() => { if (index === 1) { item.icon = $rawfile(‘VerificationCode.png’) } }) }, (item: string) => item) } .listDirection(Axis.Vertical) .scrollBar(BarState.Off) .friction(0.6) .width(‘90%’) } .width(‘100%’) .height(‘100%’) .backgroundColor(0xDCDCDC) .padding({ top: 5 }) } }
更多关于list里面button的image点击如何修改图片啊? HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
@Entry
@Component
struct Page11 {
@State message: Resource = $rawfile('ich_collect_n_24x24.png')
build() {
Column() {
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image(this.message).width(18).height(18)
}
.onClick(() => {
//这里button点击怎么才能修改上面的图片啊。。。
this.message = $rawfile('ich_collect_n_64x64.png')
})
}
.height('100%')
.width('100%')
}
}
我是list里面的 所以可能会有 几十个 。。。 而且是动态的。。。 也只能用state吗? 就没有别的语言那样获取id进行直接修改么。。。
在鸿蒙Next中,修改List
中Button
的Image
图片可以通过以下步骤实现:
-
定义图片资源:在
resources
目录下定义图片资源,如ic_new_image.png
。 -
绑定数据:在
List
的item
布局文件中,使用Image
组件作为Button
的子组件,并通过$r('app.media.ic_new_image')
绑定图片资源。 -
更新数据:在
List
的DataSource
中,通过updateData
方法更新item
的数据,修改Image
的src
属性为新图片的资源路径。 -
监听点击事件:在
List
的item
中,为Button
设置点击事件监听器,在点击时触发数据更新。
示例代码:
// 假设List的item数据结构如下
let itemData = {
id: 1,
imageSrc: $r('app.media.ic_old_image')
};
// 更新数据
function updateImage(item) {
item.imageSrc = $r('app.media.ic_new_image');
listDataSource.updateData(item);
}
// 在List的item布局中
Button() {
Image(item.imageSrc)
.width(50)
.height(50)
}
.onClick(() => {
updateImage(itemData);
});