反应路由器v4子组件

时间:2017-07-31 20:43:10

标签: reactjs react-router

import React from 'react';
import { IndexRoute, Router, Route, hashHistory } from 'react-router';
import Home from './containers/Home';
import App from './containers/App';

export default (
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Home}/>
    </Route>
  </Router>
);
import React, { Component } from 'react';
import {Background} from '../App/App.style'


class App extends Component {
  render() {
    return (
      <div>
        {this.props.children}
        {console.log(this.props.children)}
      </div>
    );
  }
}

export default App;

routerV4中这些代码的替代方案
我希望Home组件成为App Component的孩子 什么将使用而不是IndexRoute?

1 个答案:

答案 0 :(得分:0)

这就是react-router v4的工作原理。

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import App from '../App';

ReactDOM.render(
    <BrowserRouter>
       <Switch>
          <Route exact path="/" component={App} />
       </Switch>
    </BrowserRouter>
);

然后对于Home,将其导入App组件并渲染它:

import Home from './Home'
export default class App extends Component {
...
    render(){
        <Home />
    }
}

如果ypu打算在app HomeAboutApp内有多个子女,请使用:

<Switch>
     <Route path="/home" component={Home} />
     <Route path="/about" component={About} />
</Switch>

发现this repo非常有帮助。