HarmonyOS 鸿蒙Next:如何在子组件中使用父组件UI,并将子组件的值传入实时渲染更新?
HarmonyOS 鸿蒙Next:如何在子组件中使用父组件UI,并将子组件的值传入实时渲染更新?
这是父组件index.ets的代码:
import CounterExe from ‘./components/counter’;
struct Index {
@Builder test(value:number){
Column(){
Text(‘builder渲染测试:’+value.toString())
Test({ value })
}.alignItems(HorizontalAlign.Start)
}
build() {
Column() {
List() {
ListItem() {
Column() {
CounterExe({
container:()=>{},
container1:this.test,
})
}.width(‘100%’)
}
}
.width(‘100%’).height(‘100%’)
}
.height(‘100%’)
}
}
struct Test{
@Prop @Watch(‘onChange’)value:number;
onChange(){
console.log(this.value.toString())
}
build(){
Text(‘builder内嵌组件渲染测试:’+this.value.toString())
}
}
这是子组件的counter.ets代码:
export default struct CounterExe {
@State value: number = 1
@BuilderParam container: () => void // 用于占位
@BuilderParam container1: (value: number) => void // 用于实际传递参数,但只会初始化渲染
build() {
Column() {
Counter() {
Text(this.value.toString())
}
.margin(100)
.onInc(() => {
this.value++
})
.onDec(() => {
this.value–
})
.enableInc(this.value < 9)
.enableDec(this.value > 1)
Column({space:10}) {
Text(‘子组件内值:’ + this.value.toString())
this.container()
this.container1(this.value)
}.alignItems(HorizontalAlign.Start)
}
}
}
为什么子组件中this.container1渲染的value当组件内value更新时始终不会变,或者有什么办法可以实现这种场景下的数据同步?