HarmonyOS 鸿蒙Next 父组件的 builder 如果 bind 了 this,那么子组件无法重新触发其渲染
HarmonyOS 鸿蒙Next 父组件的 builder 如果 bind 了 this,那么子组件无法重新触发其渲染
请注意这行代码 builderParams: this.builderP.bind(this)
如果 bind
了,那么子组件 name
,maessge
状态变化 也无法触发 builderParams
重新渲染
业务中我遇到了需要 bind
的场景,父组件定义 builder
并且逻辑依赖父组件状态
这算 bug 嘛?
@Component
struct Child {
@Prop name: string;
@State message: string = 'Hello World'
@Builder builder($$: {
name: string,
message: string
}) {
Text($$.name + $$.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
@BuilderParam builderParams: ($$: {
name: string,
message: string
}) => void = this.builder
build() {
Column() {
Text(this.name)
this.builderParams({ name: this.name, message: this.message })
Text('child').onClick(() => {
this.name = 'yarnb'
this.message = 'gaga'
})
}
}
}
@Entry
@Component
struct TestBuilder {
@State name: string = 'yb'
@Builder builderP($$: {
name: string,
message: string
}) {
Text($$.name + $$.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.name = 'yarnb'
})
}
build() {
Row() {
Column() {
Text(this.name)
Child({
name: this.name,
builderParams: this.builderP.bind(this)
})
}
.width('100%')
}
.height('100%')
}
}
更多关于HarmonyOS 鸿蒙Next 父组件的 builder 如果 bind 了 this,那么子组件无法重新触发其渲染的实战教程也可以访问 https://www.itying.com/category-93-b0.html
我也一直没搞懂 .bind(this)
是干啥的
更多关于HarmonyOS 鸿蒙Next 父组件的 builder 如果 bind 了 this,那么子组件无法重新触发其渲染的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
去掉bind(this)不可以吗~
现在就是去掉了,通过 @link 解决状态传递问题,
在HarmonyOS中,如果父组件的builder
函数中绑定了this
,子组件可能无法重新触发渲染。这是因为builder
函数的执行依赖于父组件的状态更新。当this
被绑定后,builder
函数的上下文可能不会随着父组件状态的改变而更新,导致子组件的渲染逻辑无法正确触发。
在鸿蒙Next中,组件的渲染机制是基于状态驱动的。如果父组件的builder
函数没有正确更新,子组件的渲染也就不会触发。为了避免这种情况,开发者需要确保builder
函数的上下文能够正确响应父组件状态的变化,而不是通过绑定this
来固定上下文。
此外,鸿蒙Next的渲染机制还涉及到组件的生命周期和状态管理。如果父组件的状态更新没有正确传播到子组件,子组件的渲染逻辑也无法执行。开发者需要仔细检查父组件的状态管理逻辑,确保状态更新能够正确触发builder
函数的重新执行,从而带动子组件的重新渲染。
总之,父组件的builder
函数绑定this
可能导致子组件无法重新渲染,开发者应避免这种做法,确保builder
函数能够正确响应父组件状态的变化。