reactjs - 如何渲染实际上是组件的道具?
问题描述
我有一个子组件,我需要表现得好像它被渲染了一样。我希望在渲染之前调用这个子组件的函数(即 componentDidMount、构造函数等)
为了实现这一点,我将此子组件传递给一个<CustomRoute />
组件,根据某些条件,该组件将要么
- 直接渲染子组件,或者
- 渲染其他东西
无论哪种方式,我都需要subcomponent
事先调用的函数。我计划在子组件中完成此操作,如下所示
render() {
if(this.props.someCondition) render "";
render <div>Actual Subcomponent</div>
}
我的CustomRoute
设置如下
// App.js
import subcomponent from "./somewhere"
import CustomRoute from "./CustomRoute"
Class App.js extends React {
render() {
return <div>
<CustomRoute path='/subcomponent' component={subcomponent} isPreloaded={true}/>
</div>
}
}
问题是关于如何实现 CustomRoute
import Route from "react-router-dom"
class CustomRoute extends React {
render() {
if(this.props.isPreloaded) return this.props.component; // Is this right?
return <Route component={this.props.component} />
}
}
这个问题的 TL;DR 版本将是
如何渲染作为道具而不是导入引入的组件?
解决方案
在导入时更改
subcomponent
为Subcomponent
import Subcomponent from "./somewhere"
然后像这样传递它:
<CustomRoute path='/subcomponent' component={<Subcomponent />} isPreloaded={true}/>
- 有关更多信息,请查看此链接: 组合与继承
推荐阅读
- python - 用2种方法制作潜在向量,它们是一样的吗?
- eclipse - eclipse buildship 插件中缺少参数选项卡
- python - 将多列与另一列进行比较时立即选择更小/更大的值
- r - 多列汇总
- java - 将类的对象存储为循环内的 HashMap 的值
- ios - 加载视图控制器后,模糊视图背景变为不透明
- phpstorm - PhpStorm 协议处理程序直接从无法在 Mac 上打开文件的 URL 打开文件
- c# - Asp.net 样板中的 Elsa 工作流集成
- c++ - C++17 找到函数的确切参数并传递给模板函数
- c# - 在 C# .Net Core 中管理增量计数器的最佳方法