首页 > 解决方案 > ReactJS 组件 - 控制 ReactJS 外部的可见性

问题描述

我正在编写一个可重用的 UI 模块,它公开了用于创建窗口和管理可见性的纯 Typescript API。它在内部使用 ReactJS 的事实隐藏在实现细节中。当模块的宿主调用“createWindow”方法时,我实质上是在给定的父元素下渲染我的 ReactJS 组件。但我也希望主机也能够切换组件的可见性。我的代码的简化版本如下:

export class ApiImpl implements Api {
  public constructor() {
    this._windowMap = new Map<string, MyWindow>();
  }

  public createWindow(id: string, parentElement: HTMLElement): void {
    if (!this._windowMap.has(id)) {
      this._windowMap.set(id, new MyWindow(id, parentElement));
  }

  public toggleVisible(id: string, display?: boolean): void {
      const window: MyWindow | undefined = this._windowMap.get(id);
      if (window) {
        window.toggleVisible(display);
      }
  }

  private _windowMap: Map<string, MyWindow>;
}

export class MyWindow {
  public constructor(id: string, parentElement: HTMLElement): void {
    ReactDOM.render((
      <MyComponent id={ id } />
    ), parentElement);
  }

  public toggleVisible(display?: boolean): void {
    /* proper way to toggle visibility of component? */
  }
}

所以基本上我不确定如何从 ReactJS 组件外部控制组件的可见性。我尝试将“可见”标志传递给组件属性,如果该标志为假,则在组件上放置“显示:'无'”样式,但更新 MyWindow 中的标志不会导致组件“反应”。我是否需要使用“React.useState”或其他钩子来让组件对外部变量做出反应?

标签: reactjs

解决方案


推荐阅读