我有一个页面React app。我有一个BaseLayout组件,作为应用程序的容器。 BaseLayout显示页眉和页脚以及内容,如下所示:
class App extends Component {
render() {
return (
<div>
<BaseLayout>
</BaseLayout>
</div>
);
}
}
的baselayout
export default class BaseLayout extends Component {
render() {
return (
<div>
<NavBar />
{this.props.children}
<Footer />
</div>
)
}
}
index.js
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/page_one" component={PageOne} />
<Route path="/page_two" component={PageTwo} />
<Route path="/" component={App} />
</Switch>
</BrowserRouter>,
document.getElementById('root')
)
所有导航都在navBar.js组件内。
navBar.js
export default class NavBar extends Component {
render() {
return (
<div className="nav-bar">
<button><Link to="/">Home</Link></button>
<button><Link to="/page_one">Page One</Link></button>
<button><Link to="/page_two">Page Two</Link></button>
</div>
)
}
}
pageOne.js和pageTwo.js
export default class PageOne extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<h1>Page One </h1>
</div>
);
}
}
问题在于,当我转到page_one或page_two URL时,它只显示组件的内容而不显示导航栏。
如何使用反应路由器和反应框架在所有页面上显示导航栏和页脚?
更新:
App.js
class App extends Component {
render() {
return (
<div>
<BaseLayout>
</BaseLayout>
</div>
);
}
}
export default App;
我将index.js更改为以下内容:
ReactDOM.render(
<BrowserRouter>
<Route path="/" component={App}>
<Switch>
<Route path="/page_one" component={PageOne} />
<Route path="/page_two" component={PageTwo} />
</Switch>
</Route>
</BrowserRouter>,
document.getElementById('root')
)
现在,我得到以下内容:
如果我使用上面的代码,页面就不会出现在任何地方:
答案 0 :(得分:0)
我认为你应该提升&#34; App
作为根Route
那么App
是否与BaseLayout
相同?你的例子很难说清楚
示例:
const Index = () => {
return (
<BrowserRouter>
<div>
<Route component={App} />
<Switch>
<Route path="/page_one" component={PageOne} />
<Route path="/page_two" component={PageTwo} />
</Switch>
</div>
</BrowserRouter>
);
};
A running code example,我没有使用堆栈代码,因为我无法在此处使用带有推送状态的react-route。
我发布整个代码,以防将来破坏网址:
import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route, Link, Switch } from "react-router-dom";
const Footer = () => <div>Footer...</div>;
class BaseLayout extends React.Component {
render() {
return (
<div>
<NavBar />
{this.props.children}
<hr/>
<Footer />
</div>
);
}
}
class NavBar extends React.Component {
render() {
return (
<div className="nav-bar">
<button>
<Link to="/">Home</Link>
</button>
<button>
<Link to="/page_one">Page One</Link>
</button>
<button>
<Link to="/page_two">Page Two</Link>
</button>
</div>
);
}
}
const PageOne = () => <h1>Page One</h1>;
const PageTwo = () => <h1>Page Two</h1>;
class App extends React.Component {
render() {
return (
<div>
<BaseLayout>{this.props.children}</BaseLayout>
</div>
);
}
}
const Index = () => {
return (
<BrowserRouter>
<div>
<Route component={App} />
<Switch>
<Route path="/page_one" component={PageOne} />
<Route path="/page_two" component={PageTwo} />
</Switch>
</div>
</BrowserRouter>
);
};
render(<Index />, document.getElementById("root"));