[React] React Router: Nested Routes
React Router nested routes
2023-09-14 09:00:54 时间
Since react-router routes are components, creating nested routes is as simple as making one route a child of another in JSX.
Make the nested component:
class App extends React.Component { render(){ return( <Router history={hashHistory}> <Route path="/" component={Home}> <Route path="about" component={About}> <Route path="contact" component={Contact}></Route> </Route> </Route> </Router> ); } }
Change the path:
const Links = () => <nav > <Link activeStyle={{color: 'green'}} to="/">Home</Link> <Link activeStyle={{color: 'green'}} to="/about">About</Link> <Link activeClassName="active" to="/about/contact">Contact</Link> </nav>;
Pass the props.children to the nested component:
const Home = (props) => <div><h1>Home</h1><Links></Links>{props.children}</div>;
const About = (props) => <div><h1>About</h1>{props.children}</div>;
const Contact = () => <div><h1>Contact</h1></div>;
----------------
import React from 'react'; import {hashHistory, Route, Router, Link} from 'react-router'; // About is the child of home, to display the about, we need to access // props.children const Home = (props) => <div><h1>Home</h1><Links></Links>{props.children}</div>; const About = (props) => <div><h1>About</h1>{props.children}</div>; const Contact = () => <div><h1>Contact</h1></div>; const Links = () => <nav > <Link activeStyle={{color: 'green'}} to="/">Home</Link> <Link activeStyle={{color: 'green'}} to="/about">About</Link> <Link activeClassName="active" to="/about/contact">Contact</Link> </nav>; class App extends React.Component { render(){ return( <Router history={hashHistory}> <Route path="/" component={Home}> <Route path="about" component={About}> <Route path="contact" component={Contact}></Route> </Route> </Route> </Router> ); } } export default App;
相关文章
- react源码解析3.react源码架构
- React Router源码浅析
- React源码学习入门(一)新手如何学习React源码
- React团队是如何测试并发特性的
- React循环DOM时为什么需要添加key
- 说说React-Router底层实现?-面试进阶
- 从零手写react-router
- 升级到React-Router-v6
- 从零手写react-router
- React魔法堂:echarts-for-react源码略读
- React强制刷新组件的一种方式
- 【Web技术】1445- 如何使用 Hooks 写出高质量的 React 和 Vue 组件?
- 从实现一个React到深度理解React框架核心原理_2023-02-27
- react子父组件相互通信传值系列之——父组件传值与函数给子组
- 使用react修改ant design默认样式|自定义
- 一道React面试题把我整懵了_2023-02-28
- 阿里前端二面常考react面试题(必备)_2023-02-28
- 从零手写react-router_2023-03-01
- 如何写React前端业务代码
- React 的 setState 同步还是异步
- react的useState源码分析2
- React Router V6详解
- 从零手写react-router
- 关于 “ React 和 Vue 该用哪个” 我真的栓 Q