将子组件类作为道具传递给React中的父组件

问题描述 投票:2回答:1

如何将子组件类作为道具传递给React中的父组件。

我的父组件代码:

import React, { Component } from 'react';
import { DashBoard } from './DashBoard/DashBoard';
import { DashBoard } from './Details/Details';

class ContentArea extends Component {
  render() {
    return (
      <div className="content-wrapper">
        <DashBoard />
        <Details />
      </div>
    )
  }
}

export default ContentArea;

我的孩子组件代码:

import React, { Component } from 'react';

export class DashBoard extends Component {
  render() {
    return (
      <h1>This is DashBoard Page.</h1>
    );
  }
}

和我的Route.js代码:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import { App } from './App';
import { DashBoard } from './components/DashBoard/DashBoard';
import { Details } from './components/Details/Details';


export class AppRoute extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route exact path={'/'} component={App} />
          <Route path={'/DashBoard'} component={DashBoard} />
          <Route path={'/Details'} component={Details} />
        </div>
      </Router>
    );
  }
}

App.js:

import React, { Component } from 'react';

import SideBar from './components/SideBar';
import Footer from './components/Footer';
import Header from './components/Header/Header';
import ContentArea from './components/ContentArea';

export class App extends Component {
  render() {
    return (
      <div className="skin-purple">
        <Header />
        <SideBar />
        <ContentArea />
        <Footer/>
      </div>
    );
  }
}

现在我想将我的所有子组件作为道具传递给父组件。虽然路由子组件应该在父组件内部进行渲染。

任何人都可以帮助我如何实现这一目标?

reactjs react-router react-props
1个回答
2
投票

由于ContentArea位于App组件中,并且您希望在其中呈现DashBoardDetails,因此您可以在ContentArea级别指定嵌套路由。

export class AppRoute extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path={'/'} component={App} />
        </div>
      </Router>
    );
  }
}


import { DashBoard } from './DashBoard/DashBoard';
import { Details } from './Details/Details';
class ContentArea extends Component {
  render() {
    return (
      <div className="content-wrapper">
        <Route exact path={'/DashBoard'} component={DashBoard} />
        <Route exact path={'/Details'} component={Details} />
      </div>
    )
  }
}

export default ContentArea;
© www.soinside.com 2019 - 2024. All rights reserved.