如果您的应用具有以下路线,那么设置组件的正确方法是什么。
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更改div中的内容
我有组件有形式。
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?
如果你没有在顶层使用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;