(为清晰起见而更新)我的应用程序具有以下结构:
<Layout />
/components/
<Header />
<Navigation />
<Stage />
<Footer />
/pages/
<Home />
<About />
<Contact />
我的想法是将<Navigation>
元素隔离,并导入父<Header>
(以及后来的站点地图)。然后将所有组件转移到父<Layout>
中,并将其输入<div id="root">
使用下面的代码成功调用和呈现my / pages / Components的内容。但是,此页面内容在我的<header>
元素内部呈现,从而破坏了页面层次结构。
我的目的是让<Switch>
设备在<Stage>
父组件中呈现/ pages / Components。
任何将<Switch>
元素移动到<Stage>
组件的尝试都会导致整个应用无法加载/呈现。
import React from 'react';
import {
BrowserRouter as Router, Route, Link, Switch
} from 'react-router-dom';
import Home from './../pages/Home';
import About from './../pages/About';
import Contact from './../pages/Contact';
export default class Navigation extends React.Component {
render() {
return (
<Router>
<div className="navigation">
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
{/*
Below should be repositioned outside of <header>, in Stage component
*/}
<div className="stage">
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</div>
</Router>
)
}
}
我的问题是:当从<Stage>
组件中选择时,如何让路由器在<Navigation>
组件中呈现所需的/ page / Components。
由于所有 reacttraining.com 示例都是单页,我很难确定我是否在假设我的应用程序应该如何优化构造或编程错误时犯了一个逻辑错误用react-router v4重建两个元素之间的关系。
答案 0 :(得分:4)
您需要做的就是在标题中包含div
时将这两个stage
分开。由于组件需要在单个元素中呈现,因此整个内容需要另外div
:
export default class Navigation extends React.Component {
render() {
return (
<Router>
<div>
<div className="navigation">
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
</div>
<div className="stage">
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</div>
</Router>
);
}
}
<强>更新强> 更新我的回答:
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
const Header = () => <h1>I'm a header</h1>;
const Navigation = () => (
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
);
const Stage = () => (
<div>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</div>
);
const Footer = () => <h6>Footer</h6>;
const Home = () => <h3>Home</h3>;
const About = () => <h3>About</h3>;
const Contact = () => <h3>Contact</h3>;
const App = () => (
<Router>
<div>
<Header />
<Navigation />
<Stage />
<Footer />
</div>
</Router>
);
render(<App />, document.getElementById('root'));