【问题标题】:React - Correct way of passing a reference to a react-portalReact - 将引用传递给反应门户的正确方法
【发布时间】:2023-04-07 14:46:01
【问题描述】:

我有一个卡片组件需要触发一个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 组件一起使用。为了完成它,我需要两个组件处于同一级别(兄弟姐妹)。


所以我对 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,但我认为这不是一个好习惯。

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

【问题讨论】:

    标签: javascript reactjs redux portal-system


    【解决方案1】:

    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 我也是从上面得到的示例代码。

    【讨论】:

    • 嗨@Rowan,这很有趣!我在理解这种方法时遇到了一些麻烦:我的 Card 组件如何访问 App 组件的引用?也许我错过了一些东西。据我了解,这会创建一个只能由连接的组件访问的引用。因此,如果我以这种方式连接 App 组件,它将引用自身。那我可以传给孩子吗? Card 组件如何访问此引用?谢谢! :)
    • 抱歉回复晚了,我在山上,服务参差不齐。我相信类似于App.getWrappedInstance().refs['selector'] 的东西。虽然通常我会将孩子的 ref 暴露给父母,但我认为这应该可行。
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多