導航路由器
Framework7-React 作為 Framework7 本身,附帶強大且靈活的路由器。而要讓它運作,我們必須指定 路由。
Framework7-React 中唯一的不同是,在 React.js 中,我們已經使用 React 元件來組成應用程式,因此我們需要將我們的頁面(React 元件)對應到路徑。這可以使用 route 的 component
屬性中傳遞 React 元件來完成。以下是基本範例
// App.jsx
// Import pages components
import HomePage from 'home.jsx';
import AboutPage from 'about.jsx';
import LoginPage from 'login.jsx';
/*
Now we need to map components to routes.
We need to pass them along with the F7 app parameters to <App> component
*/
const f7params = {
name: 'My App',
// specify routes for app
routes: [
{
path: '/',
component: HomePage,
},
{
path: '/about/',
component: AboutPage,
},
{
path: '/login/',
component: LoginPage,
},
],
};
export default () => (
<App { ...f7params }>
{/* Current View/Router, initial page will be loaded from home.jsx component */}
<View main url="/" />
</App>
)
// home.jsx
export default () => (
<Page name="home">
<Navbar title="Home Page" />
...
<Link href="/about/">About Page</Link>
<Link href="/login/">Login Page</Link>
</Page>
)
// about.jsx
export default () => (
<Page name="about">
<Navbar title="About" />
{/* Page content */}
...
</Page>
)
// login.jsx
export default () => (
<Page name="login">
<Navbar title="Login" />
{/* Page content */}
...
</Page>
)
傳遞屬性給元件
可以將元件屬性傳遞給路由器載入的 React 元件。有幾種方法可以做到這一點。
首先,所有路由參數都會自動作為屬性傳遞給元件,例如
// route with params
{
path: '/blog/:postId/comments/:commentId/',
component: BlogPost,
}
因此,如果我們透過 /blog/45/comments/122/
URL 導航,則下列資料會傳遞給屬性
{
postId: '45',
commentId: '122',
}
另一個選項是在路由的 options
中指定屬性
{
path: '/some-page/',
component: SomeComponent,
options: {
props: {
foo: 'bar',
bar: true,
},
},
}
最後,當我們使用 API 導航時,可以動態地將屬性傳遞給路由元件
f7router.navigate('/some-page/', {
props: {
foo: 'bar',
bar: true,
}
})
非同步延遲載入元件
使用 Webpack 時,可以依需求載入頁面元件,例如,可以使用 F7 的路由 asyncComponent
{
path: '/about/',
asyncComponent: () => import('./pages/about.jsx'),
},
或者,如果我們需要更多控制權,可以使用 async
路由
{
path: '/about/',
async({ resolve }) {
// dynamic import component; returns promise
const reactComponent = () => import('./pages/about.jsx');
// resolve promise
reactComponent().then((rc) => {
// resolve with component
resolve({ component: rc.default })
});
} ,
},
路由器 API
若要存取路由器實例並使用 路由器 API,可以使用元件的特殊 f7router 元件屬性
export default ({ f7router }) => {
return (
<Page>
<Link onClick={() => f7route.navigate('/about/')}>About</Link>
<Link onClick={() => f7route.back()}>Back</Link>
</Page>
)
}
請注意,f7route
和 f7router
元件屬性僅在根據路由載入的客製化頁面元件中可用。在父元件(例如在 View 中,或在您初始化 React 應用程式實例的地方)和子元件中,它們不可存取。因此,在這種情況下,請使用已初始化的 檢視實例,例如 f7.views.main.router