[英]Using ReactJS, how can I use Route to display different components?
我是 ReactJS 的新手,並試圖確定我是否可以將它用於我正在構建的應用程序。
我已經創建了登錄和注冊頁面,但是我在這兩個頁面中都有一些相同的代碼,我想重新使用它。
所以,目前,我有兩個獨立的頁面,構建為組件,並像這樣路由:
const App = () => (
<Router>
<div>
<Route path={ROUTES.REGISTER} component={RegisterPage} />
<Route path={ROUTES.SIGNIN} component={SignInPage} />
<Route component={SignInPage} />
</div>
</Router>
);
所以如果我 go 到 /register 我看到 RegisterPage 組件,如果我 go 到 /signin 我看到 SignInPage 組件。 (如果我 go 到其他任何東西,我會看到 SignInPage。)
但是,我還有幾個頁面要添加,風格相同,我希望能夠有一個通用的“登陸頁面”,在其中顯示適當的組件。 然后,一旦用戶登錄,我想要一個顯示適當組件的“儀表板頁面”。
因此,LandingPage 和 DashboardPage 將只是其他組件的包裝器,我希望 Routes 像這樣工作:
'landingpage/SignInPage' - 顯示 LandingPage 樣式,SignIn 組件位於 'landingpage/Register' - 顯示 LandingPage 樣式,Register 組件位於 'landingpage' - 顯示 LandingPage 樣式,SignIn 組件位於 'dashboardpage/' - 顯示默認儀表板
我以為我可以做這樣的事情:
const App = () => (
<Router>
<div>
<Route path={ROUTES.LANDINGPAGE} component={LandingPage} subPage={SignInForm} />
<Route path={ROUTES.REGISTER} component={LandingPage} subPage={RegisterForm} />
<Route path={ROUTES.SIGNIN} component={LandingPage} subPage={SignInForm} />
<Route path={ROUTES.DASHBOARD} component={DashboardPage} subPage={Overview} />
<Route component={LandingPage} subPage={SignInForm} />
</div>
</Router>
);
但我無法計算出確切的語法。 “子頁面”是否作為 state 或道具傳入? 如何使用它來正確呈現頁面?
我在網上找不到任何東西來告訴我如何做到這一點,這讓我覺得我可能走錯了路。 如果是這樣,正確的方法是什么?
您需要使用渲染道具將自定義道具傳遞給渲染組件
const App = () => (
<Router>
<div>
<Route path={ROUTES.LANDINGPAGE} render={(rProps) => <LandingPage {...rProps} subPage={SignInForm} />}/>
<Route path={ROUTES.REGISTER} render={(rProps) => <LandingPage {...rProps} subPage={RegisterForm} />}/>
<Route path={ROUTES.SIGNIN} render={(rProps) => <LandingPage {...rProps} subPage={SignInForm} />}} subPage={SignInForm} />
<Route path={ROUTES.DASHBOARD} render={(rProps) => <DashboardPage {...rProps} subPage={Overview} />}} />
<Route render={(rProps) => <LandingPage {...rProps} subPage={SignInForm} />} />
</div>
</Router>
);
但是,您可以編寫一個自定義 Route,將 LandingPage 呈現為如下布局
const RouteWithLayout = ({subPage, component: Component,...props}) => {
return <Route {...props} render={(rProps) => <Component {...rProps} subPage={subPage} />} />
}
並像使用它一樣
const App = () => (
<Router>
<div>
<RouteWithLayout path={ROUTES.LANDINGPAGE} component={LandingPage} subPage={SignInForm} />
<RouteWithLayout path={ROUTES.REGISTER} component={LandingPage} subPage={RegisterForm} />
<RouteWithLayout path={ROUTES.SIGNIN} component={LandingPage} subPage={SignInForm} />
<RouteWithLayout path={ROUTES.DASHBOARD} component={DashboardPage} subPage={Overview} />
<RouteWithLayout component={LandingPage} subPage={SignInForm} />
</div>
</Router>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.