首页 > 解决方案 > 如何渲染实际上是组件的道具?

问题描述

我有一个子组件,我需要表现得好像它被渲染了一样。我希望在渲染之前调用这个子组件的函数(即 componentDidMount、构造函数等)

为了实现这一点,我将此子组件传递给一个<CustomRoute />组件,根据某些条件,该组件将要么

  1. 直接渲染子组件,或者
  2. 渲染其他东西

无论哪种方式,我都需要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 版本将是

如何渲染作为道具而不是导入引入的组件?

标签: reactjsroutes

解决方案


  • 在导入时更改subcomponentSubcomponent

    import Subcomponent from "./somewhere"
    

然后像这样传递它:

   <CustomRoute path='/subcomponent' component={<Subcomponent />} isPreloaded={true}/>

推荐阅读