如果您的应用具有以下路线,则正确的组件设置方法是什么。
App.js
import React, { Component } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Navbar from "./components/layouts/Navbar";
import Home from "./components/pages/Home";
import About from "./components/pages/About";
import Dashboard from "./components/dashboard/Dashboard";
import Footer from "./components/layouts/Footer";
import "./App.css";
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
<Route exact path="/dashboard" component={Dashboard} />
{/*
Do i do this
<Route exact path="/dashboard/resource/create" component={Form} />
*/}
</Switch>
<Footer />
</div>
</Router>
);
}
}
export default App;
Dashboard.js
import React, { Component } from "react";
import Sidebar from "./Sidebar";
import Main from "./Main";
class Dashboard extends Component {
render() {
return (
<div className="container">
<div className="row">
<div id="sidebar" className="col-md-3">
<Sidebar />
</div>
<div id="main" className="col-md-9">
<Main />
</div>
</div>
</div>
);
}
}
export default Dashboard;
当用户转到 exampleapp.dev/dashboard/resource/create
我只想在div中更改ID为main
的内容我的组件具有形式。
Form.js
import React, {Component} from 'react';
class Form extends Component {
render() {
return (
<div>
<h1>Form goes in here</h1>
</div>
);
}
}
export default Form;
我是否必须创建一个名为CreateResource.js的新组件并重复Dashboard.js中的所有内容,然后将
换出执行此操作的正确方法是什么?使用react-router-dom吗?
答案 0 :(得分:0)
如果不使用顶层的nested routes
属性,则可以使用exact
。此外,Switch
组件还允许您仅渲染一个Route
,因此您可以对路径进行重新排序,使带有其他路径的前缀路径的路径位于末端
<Router>
<div className="App">
<Navbar />
<Switch>
<Route exact path="/about" component={About} />
<Route path="/dashboard" component={Dashboard} />
<Route exact path="/" component={Home} />
</Switch>
<Footer />
</div>
</Router>
您将在仪表板组件中拥有
class Dashboard extends Component {
render() {
return (
<div className="container">
<div className="row">
<div id="sidebar" className="col-md-3">
<Sidebar />
</div>
<div id="main" className="col-md-9">
<Switch>
<Route path="/dashboard/resource/create" component={Form} />
<Route component={Form} />
</Switch>
</div>
</div>
</div>
);
}
}
export default Dashboard;