我对React还是很陌生,我正在尝试使用react-bootstrap实现Navbar。我已经设置了导航栏,但实际上没有链接到我的任何页面。
我尝试浏览文档,但是那里没有太多信息。我看过其他文章,但他们似乎都在使用旧版本的react-bootstrap或根本不使用它。
range
import React from "react";
import ReactDOM from "react-dom";
import "./components/stylesheets/index.css";
import * as serviceWorker from "./serviceWorker";
import "bootstrap/dist/css/bootstrap.min.css";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("root"));
serviceWorker.unregister();
import React, { Component } from "react";
import "./components/stylesheets/App.css";
import NavBar from "./components/NavBar";
import Home from "./components/Home";
import About from "./components/About";
class App extends Component {
render() {
return <NavBar />;
}
}
export default App;
我希望该应用自动打开主页,然后在navBar中单击该按钮,然后打开其他页面。
答案 0 :(得分:1)
编辑:我创建了一个工作示例,您可以检查代码:Codesandbox
react-router
处理链接。
首先,您需要使用BrowserRouter包装组件,如下所示:
import { BrowserRouter } from "react-router-dom";
import App from "./App";
const app = (
<BrowserRouter>
<App />
</BrowserRouter>
);
ReactDOM.render(app, document.getElementById("root"));
在NavBar.js
组件内的<Switch />
中,声明路由:
import { Switch, Route, Link } from "react-router-dom";
//(...)
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
在您的情况下,请在Nav.Link中使用Link
组件:
<Nav className="ml-auto">
<Nav.Link as={Link} to="/">Home</Nav.Link>
<Nav.Link as={Link} to="/about">About</Nav.Link>
</Nav>
如果要向NavBar添加更多链接,则同样适用。
答案 1 :(得分:0)
使用react-bootstrap用于导航栏的示例应用程序
App.js
function App() {
return (
<div>
<Router>
<NavBar />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/updates" exact component={Updates} />
<Route path="/profile" exact component={Profile} />
</Switch>
</Router>
</div>
);
}
const Home = () => <h1>Home</h1>;
const About = () => <h1>About</h1>;
const Updates = () => <h1>Updates</h1>;
const Profile = () => <h1>Profile</h1>;
NavBar.js
class NavBar extends React.Component {
state = {};
render() {
return (
<div id="bar">
<Navbar bg="light" variant="light">
<Navbar.Brand href="/">CALC-U</Navbar.Brand>
<Nav className="ml-auto">
<Nav.Link href="/">Home</Nav.Link>
<Nav.Link href="/about">About</Nav.Link>
<Nav.Link href="/updates">Updates</Nav.Link>
<Nav.Link href="/profile">Profile</Nav.Link>
</Nav>
</Navbar>
</div>
);
}
}