导航路由器
Framework7-React 与 Framework7 本身一样,自带强大且灵活的路由器。为了使其工作,我们必须指定路由.
Framework7-React 的唯一区别在于,在 React.js 中我们已经用 React 组件组合我们的应用程序,因此我们需要将我们的页面(React 组件)映射到路由。这可以通过传递 React 组件来完成component
属性中传递 Svelte 组件来完成。这里有一个基本示例:
// 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,
},
},
}
中指定属性
f7router.navigate('/some-page/', {
props: {
foo: 'bar',
bar: true,
}
})
异步懒加载组件
With Webpack it is possible to load page components on demand, it is possible with F7's route asyncComponent
, for example:
{
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 应用程序实例的地方)和子组件中不可访问。因此在这种情况下使用访问初始化View 实例的访问,例如f7.views.main.router