导航路由器
Framework7-React 作为 Framework7 本身附带一个功能强大且灵活的路由器。要使其正常工作,我们必须指定路由。
Framework7-React 中唯一的区别在于在 React.js 中,我们已经使用 React 组件编写应用程序,因此我们需要将页面(React 组件)映射到路由。可以通过在路由的 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
组件 prop 仅在您根据路由加载的自定义页面组件中可用。在父组件(例如在 View 中,或者在您初始化 React 应用实例的位置)以及在子组件中,它们不可访问。因此,在这种情况下,使用对已初始化的View 实例的访问,例如f7.views.main.router