javascript - React - 将引用传递给 react-portal 的正确方法

标签 javascript reactjs redux portal-system

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

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

这是我的 App 组件:

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 组件一起使用。为了完成它,我需要两个组件处于同一级别( sibling )。


所以我对 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 元素中。


问题

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

问题是 App 组件和 Card 组件真的相距甚远。将 App 组件的引用传递给所有子组件,直到到达 Card 组件,这有点荒谬。

我也可以将它保存到 Redux Store 中,但我认为这不是一个好的做法。

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

最佳答案

Redux 提供了传递引用的功能,而无需将它们显式保存在商店中。

您可以在 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 我也从中获得了上面的示例代码。

关于javascript - React - 将引用传递给 react-portal 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51801687/

相关文章:

javascript - ZeroClipboard - 如何使用

javascript - 如何在此 Angular 2 样本上使用 HTML5 模式?

javascript - 窗口滚动事件已停止在整个域的所有实现上触发

reactjs - Formik - 在 API 调用后更新初始值

javascript - React/Redux 获取和过滤数据

javascript - --如何访问此顶级文件中的容器/存储?

javascript - 从对象数组添加标记

reactjs - 用户输入使用表单中的reactjs创建饼图

javascript - 根据 Redux 操作负载从数组中删除项目

javascript - 发送多个最终提交表单的 AJAX 请求会导致意外结果