@Event实现子传父
类似于vue的子传父,在鸿蒙中可以使用状态管理V2提供的@Event
实现父子组件数据传递。
需要做以下事情:
- 父组件props传参的时候重写子组件的操作函数
- 子组件用
@Event
修饰该函数,表示需要传入更新数据源的回调函数
@Entry
@ComponentV2
struct Index {
@Local title: string = "Titile One";
@Local fontColor: Color = Color.Red;
build() {
Column() {
Child({
title: this.title,
fontColor: this.fontColor,
changeFactory: (type: number) => {
if (type == 1) { // 操作对应数据
this.title = "Title One";
this.fontColor = Color.Red;
} else if (type == 2) {
this.title = "Title Two";
this.fontColor = Color.Green;
}
}
})
}
}
}
@ComponentV2
struct Child {
@Param title: string = '';
@Param fontColor: Color = Color.Black;
@Event changeFactory: (x: number) => void = (x: number) => {
}; // 回调函数的自定义实现(不写会自动生成一个默认函数)
build() {
Column() {
Text(`${this.title}`)
.fontColor(this.fontColor)
Button("change to Title Two")
.onClick(() => {
this.changeFactory(2);
})
Button("change to Title One")
.onClick(() => {
this.changeFactory(1);
})
}
}
}
这样子组件就可以调用父组件上重写的changeFactory
函数去修改父组件的相应数据。
做出更改和传会子组件是异步的
调用回调函数后父组件的值会立刻更改,但是只有在父组件决定实际处理后才会在渲染前传回子组件。
官方文档的示例:
@ComponentV2
struct Child {
@Param index: number = 0;
@Event changeIndex: (val: number) => void;
build() {
Column() {
Text(`Child index: ${this.index}`)
.onClick(() => {
this.changeIndex(20);
console.log(`after changeIndex ${this.index}`); // 还是0
})
}
}
}
@Entry
@ComponentV2
struct Index {
@Local index: number = 0;
build() {
Column() {
Child({
index: this.index,
changeIndex: (val: number) => {
this.index = val;
console.log(`in changeIndex ${this.index}`); // 20——父组件值立刻更改
}
})
}
}
}