首页 > 解决方案 > React - 将引用传递给反应门户的正确方法

问题描述

我有一个Card组件需要触发Modal组件。

我还有一个通用的Overlay组件,用于在我的应用程序上方显示一些内容。

这是我的应用程序组件:

class App extends Component {
  /* Some Code */
  render() {
    return (
      <div className="c-app">
        <Content /> {/* Our content */}
        <Overlay /> {/* Our all-purpose-overlay */}
        {/* I want my Modal here */}
      </div>
    )
  }
}

我想将我的Overlay组件与我的Modal组件一起使用。为了完成它,我需要同一级别的两个组件(兄弟姐妹)。


所以我对react-portals做了一些研究,我发现我可以在我的Card组件中执行以下操作:

class Card extends Component {
  constructor() {
    super();
    this.state = { showModal: false }
  }

  render() {
    const { showModal } = this.state;
    return (
      {/* Some code */}
      {
        showModal 
          && ReactDOM.createPortal(
            <Modal>{* ... *}</Modal>,
            document.body
          )
      }
    );
  }
}

在上面的示例中,我将Modal发送到body元素中。


问题

如何在不通过道具发送的情况下获取对App组件的引用?

问题是App组件和Card组件相距甚远。将App组件的引用通过所有子组件向下发送,直到到达Card组件,这有点可笑。

我也可以将它保存到Redux Store,但我认为这不是一个好习惯。

我应该如何解决这个问题?谢谢!

标签: javascriptreactjsreduxportal-system

解决方案


Redux 提供了传递 ref 的功能,而无需将它们显式保存在 store 中。

您可以在 connect() 调用中将 withRef 选项设置为 true:

connect(null, null, null, { withRef: true })(<Your component>);

并通过以下方法访问 ref:

ref={connectedComponent =>
        this.<Your component>=
        connectedComponent.getWrappedInstance();

这篇中等文章可能会有所帮助。 https://itnext.io/advanced-react-redux-techniques-how-to-use-refs-on-connected-components-e27b55c06e34 我也是从上面得到的示例代码。


推荐阅读