# Router ## API ### 初始化 ```tsx | pure const app = new Application({ router: { type: 'browser' // type 的默认值就是 `browser` } }) // or const app = new Application({ router: { type: 'memory', initialEntries: ['/'] } }) ``` ### 添加路由 #### 基础用法 ```tsx | pure import { RouteObject } from 'react-router-dom' const app = new Application() const Hello = () => { return
Hello
} // 第一个参数是名称, 第二个参数是 `RouteObject` app.router.add('root', { path: '/', element: }) app.router.add('root', { path: '/', Component: Hello }) ``` #### 支持 Component 是字符串 ```tsx | pure // register Hello app.addComponents({ Hello }) // Component is `Hello` string app.router.add('root', { path: '/', Component: 'Hello' }) ``` #### 嵌套路由 ```tsx | pure import { Outlet } from 'react-router-dom' const Layout = () => { return
Home about
} const Home = () => { return
Home
} const About = () => { return
About
} app.router.add('root', { element: }) app.router.add('root.home', { path: '/home', element: }) app.router.add('root.about', { path: '/about', element: }) ``` 它将会被渲染为如下形式: ```tsx | pure { element: , children: [ { path: '/home', element: }, { path: '/about', element: } ] } ``` ### 删除路由 ```tsx | pure // 传递 name 即可删除 app.router.remove('root.home') app.router.remove('hello') ``` #### 插件中修改路由 ```tsx | pure class MyPlugin extends Plugin { async load() { // add route this.app.router.add('hello', { path: '/hello', element:
hello
, }) // remove route this.app.router.remove('world'); } } ``` ## 示例 ```tsx /** * defaultShowCode: true */ import React from 'react'; import { Link, Outlet } from 'react-router-dom'; import { Application } from '@nocobase/client'; const Home = () =>

Home

; const About = () =>

About

; const Layout = () => { return
Home, About
} const app = new Application({ router: { type: 'memory', initialEntries: ['/'] } }) app.router.add('root', { element: }) app.router.add('root.home', { path: '/', element: }) app.router.add('root.about', { path: '/about', element: }) export default app.getRootComponent(); ```