【问题标题】:How to pass data from functional component to class component in reactjs?reactjs中如何将数据从功能组件传递到类组件?
【发布时间】:2020-05-06 07:14:58
【问题描述】:

我想将我的 App.js 文件中的数据传递给子类组件。我尝试过使用道具,但它根本不起作用

const org = 'Organization Dashboard'
const remotes = 'FromAdmin';
const DashboardContainer = ()=>(
  <Sidebar org={org}>
  <div className="App">
    <Route path='/dashboard' component={Dashboard}/> 
    <Route path='/mytab' component={MyTab}/>
    <Route path='/team' component={MyTeam}/>
    <Route path='/settings' component={Settings}/>
    <Route path='/logout' component={Logout}/>
    <Route path='/team-settings/:param1' component={TeamSettings}/>
    **<Route remotes='remotes' path='/user-settings/:param1'   component={MyTab}/>**
  </div>
  </Sidebar>
)

我想在 MyTab 类组件中传递数据,当我在 myTab 中使用 this.props 时,它显示未定义

我们将不胜感激

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    我假设您正在尝试将remotes='remotes' 传递给MyTab。由Route 渲染的组件仅传递route props,但您可以使用匿名内部函数来插入额外的道具。 如果需要,不要忘记传递路线道具!

    <Route
      path='/user-settings/:param1'
      component={routeProps => <MyTab {...routeProps} remotes='remotes' />}
    />
    

    【讨论】:

    • 太好了,别忘了将问题标记为已回答/已解决。
    【解决方案2】:

    您可以覆盖组件。默认情况下,组件接受基于类或基于函数的组件。但是您可以覆盖 组件。您不仅可以传递函数的数据。但你不应该这样做。使用 redux 来实现这种事情。如果是静态数据,那么你可以通过这种方式。但如果它是 动态数据,那么请改用 redux

    <Route
        path = '/myTab'
        component = {(props) => <MyTab {...props} data={data}/>}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-08
      • 2019-11-09
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多