HarmonyOS如何手动重置自定义组件?

应用正在开发聊天界面的一多适配,其中联系人列表和聊天界面为已有组件,需要实现复用。在手机小屏场景下,点击联系人后会跳转至聊天界面,关闭聊天界面后返回联系人列表,此场景下,每次进入聊天界面都是重新打开聊天组件并渲染,会执行聊天组件的相关生命周期。在折叠屏或者平板场景下,联系人列表和聊天界面在同屏下左右分布,因此在点击列表中联系人是,只是向聊天界面传递联系人参数,聊天界面会根据传递进来的属性做相关更新。问题:聊天界面上,状态参数较多,若通过代码重置状态变量相对困难,是否有方案可以实现令组件自动充值并执行完成生命周期?

阅读 494
1 个回答

使用NodeContainer+NodeController的方式进行控制,demo参考如下:

import { UIContext } from '@ohos.arkui.UIContext'; 
import { NodeController, BuilderNode, FrameNode } from '@ohos.arkui.node'; 
declare class Params { 
  componentId: number 
} 
@Entry 
@Component 
struct Index { 
  @State componentId: number = 1 
  @State baseNode: MyNodeController = new MyNodeController(this.componentId) 
  build() { 
    Column() { 
      Button('联系人1') 
        .onClick(() => { 
          if(this.componentId !== 1){ 
            this.componentId = 1; 
            this.baseNode.update(this.componentId).rebuild() 
          } 
        }) 
      Button('联系人2') 
        .onClick(() => { 
          if(this.componentId !== 2){ 
            this.componentId = 2; 
            this.baseNode.update(this.componentId).rebuild() 
          } 
        }) 
      NodeContainer(this.baseNode) 
    } 
  } 
} 
@Component 
struct ChildComponent { 
  @Prop componentId: number 
  @State number: number = 0 
 
  build() { 
    Column() { 
      Button(`联系人${this.componentId} ++`) 
        .onClick(() => { 
          this.number ++; 
        }) 
      Text(`计数:${this.number}`) 
    } 
  } 
} 
@Builder 
function ChildBuilder(params: Params) { 
  Row(){ 
    ChildComponent(params) 
  } 
} 
class MyNodeController extends NodeController { 
  componentId: number = 1 
  constructor(componentId: number) { 
    super(); 
    this.componentId = componentId; 
  } 
  private rootNode: BuilderNode<[Params]> | null = null; 
  private wrapBuilder: WrappedBuilder<[Params]> = wrapBuilder(ChildBuilder); 
  update(componentId: number) { 
    this.componentId = componentId; 
    return this; 
  } 
  makeNode(uiContext: UIContext): FrameNode | null { 
    if (this.rootNode === null) { 
      this.rootNode = new BuilderNode(uiContext); 
    } 
    this.rootNode.build(this.wrapBuilder, { componentId: this.componentId }) 
    return this.rootNode.getFrameNode(); 
  } 
}

上述demo模拟为切换联系人后重置聊天组件内部状态,使用NodeContainer进行占位,在点击上方两个按钮时进行切换,切换时,更新baseNode类中的参数并rebuild,实现自定义组件的重置。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进