React router v4渲染元素内部的组件

时间:2017-04-22 17:55:07

标签: javascript reactjs react-router

我使用的是最新版本的React Router v4,我尝试在PageWrap div中渲染我的页面组件Home / About,但我遇到的问题是如果我将路由添加到我的标题中,那么它将切换路由,但它们将显示Home / About组件作为标题的一部分,而不是我希望它们在哪里。

如果我将路线放入PageWrap,那么路由器不起作用,但不会在控制台上抛出任何错误。

如何在PageBody div中显示和切换组件?

Webpack link

app.js

import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import styled from 'styled-components'
import Header from './Header'

import Home from './pages/Home'
import About from './pages/About'


const Wrapper = styled.div`
  display:flex;
  min-height:100vh;
 flex:1;
 background:#eee;
`
const PageWrap = styled.div`
 margin:0 auto;
 min-width:1400px;
 background: #000;
`

class App extends React.Component { // eslint-disable-line react/prefer-
stateless-function
  render() {
    return (
  <div>
    <Header />
    <Wrapper>
      <PageWrap>
        <Router>
          <Switch>
            <Route exact path="/login" component={Home} />
            <Route exact path="/frontpage" component={About} />
            <Route exact path="/logout" render={() => (<div>logout</div>)} />
          </Switch>
        </Router>
      </PageWrap>
    </Wrapper>
  </div>
)
}
}
export default App

Header.js

import React from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import styled from 'styled-components'
import Home from '../pages/Home'
import About from '../pages/About'
import Topics from '../pages/Topics'

const Wrapper = styled.div`
  width:100%;
  height:100px;
  background:papayawhip;
`

 class Header extends React.Component { // eslint-disable-line react/prefer-
 stateless-function
  render() {
   return (
   <Router>
    <Wrapper>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/about">About</Link></li>
      <li><Link to="/topics">Topics</Link></li>
      <Route exact path="/" component={Home} />
      <Route exact path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </Wrapper>
  </Router>
  )
  }
}


export default Header

home.js

const Home = () => (<div>Home</div>)

About.js

const About = () => (<div>About</div>)

2 个答案:

答案 0 :(得分:5)

您的应用只需要一个<Router>,它应该将所有<Route /><Link/>组件包装在组件树中。

因此,你在App组件中的渲染方法应该是这样的。

render() {
  return (
    <Router>
      <div>
        <Header />
        <Wrapper>
          <PageWrap>
            <Switch>
              <Route exact path="/login" component={Home} />
              <Route exact path="/frontpage" component={About} />
              <Route exact path="/logout" render={() => (<div>logout</div>)} />
            </Switch>
          </PageWrap>
        </Wrapper>
      </div>
    </Router>)
}

并确保从您的标头组件中删除<Router>和所有<Route>

更新了WebpackBin:https://www.webpackbin.com/bins/-KiLrUNoJVxxLhL8UWx1

答案 1 :(得分:0)

有时,当您拥有“数十或数百”或路由时,可能要委派路由。

您可以see that referred to here as child routing