javascript - 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,但我认为这不是一个好习惯。
我应该如何解决这个问题?谢谢!
解决方案
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 我也是从上面得到的示例代码。
推荐阅读
- sql - 根据现有表和另一个表的条件更新表列
- php - 单击导出 excel 按钮时如何传递链接参数?
- javascript - 如何通过 Symfony 表单(使用 JS、AJAX)操作数据?
- r - 如何在嵌套函数中将所有可能的内容传递给 i、j 和 by?
- javascript - 如何仅更改输入表单控件的错误消息颜色
- sql-server - 无法连接到 localhost/127.0.0.1:44326
- php - PHP 中的 Segfault 没有 php 错误日志。如何调试?
- python - NameError:名称'run_once'未在python中定义
- c# - 将 UTF8 文本编码为 Unicode C#
- php - 如何在 Php 中缩进一个长的三元条件?