在React

时间:2017-12-22 06:43:58

标签: reactjs react-router react-props

如何将子组件类作为道具传递给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>
    );
  }
}

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

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分: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;