[英]Pass custom Props to Private Route - React Typescript
我們有一個 React 組件XYZ
,它具有某些 UI,需要根據已安裝組件的路由隱藏/顯示。
例如,如果路線是/show -> 如果路線是/hide-> 它應該顯示一個表格,如果路線是/hide-> 它應該隱藏表格。
正在使用 react-router-dom,但不想在 history.push(...) 中使用 state。
我正在尋找一種在定義路線時可以實現的解決方案,這樣以后使用此路線的任何開發人員都不必擔心維護 state。
PS:我們在 TS 中使用 Private Route,除非使用any
方法,否則無法覆蓋 render 方法。
interface PrivateRouteProps extends RouteProps {
}
const PrivateRoute: FunctionComponent<PrivateRouteProps> = ({
component: Component,
...rest
}) => {
if (!Component) return null;
return (
<Route
{...rest}
render={(props) => true
? <Component {...props}/> // looking for a way to pass custom props here
: <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
/>
)
}
用法:
<PrivateRoute path='/show' component={XYZ} />
關於如何在此 PrivateRoute 中傳遞道具然后將其傳遞給組件的任何幫助將不勝感激。TIA
我假設額外的道具是已知的並且可以作為道具傳遞給PrivateRoute
組件。
我們將type PrivateRouteProps
定義為泛型,這取決於ExtraProps
的類型。 它將附加傳遞的道具作為 object 使用道具名稱extraProps
。
我們的PrivateRouteProps
將接受除了component
之外的所有普通RouteProps
,因為我們想用我們自己的定義覆蓋它。 我們的component
版本采用典型的RouteComponentProps
和ExtraProps
(作為頂級道具)。
type PrivateRouteProps<ExtraProps> = Omit<RouteProps, 'component'> & {
component: ComponentType<RouteComponentProps & ExtraProps>
extraProps: ExtraProps;
}
在我們的render
function 中,我們可以通過檢查 props.match.path 的值來實現show
/ hide
切換,該值RouteComponentProps
props.match.path
提供。
當我們調用Component
時,我們將提供給render
器的所有 props 以及我們傳入的所有extraProps
傳遞給PrivateComponent
。 我們根本不需要重寫render
的定義,我們只是在給定的基礎上添加我們自己的額外道具。 如果我們不這樣做,我們會收到錯誤,因為我們鍵入了Component
,因此它期望接收ExtraProps
。
我們的PrivateRoute
是通用的,因此我們不會將組件本身鍵入為FunctionComponent
,而是鍵入 props。
const PrivateRoute = <ExtraProps extends {}>({
component: Component,
extraProps,
...rest
}: PrivateRouteProps<ExtraProps>) => {
if (!Component) return null;
return (
<Route
{...rest}
render={(props) => props.match.path.startsWith('/show')
? <Component {...extraProps} {...props}/>
: <Redirect to={{ pathname: '/', state: { from: props.location } }} />}
/>
)
}
現在,當我們聲明PrivateRoute
時,我們必須始終傳遞適當的額外道具。
const RenderNumber = ({n}: {n: number}) => (
<div>{n}</div>
)
<PrivateRoute path="/show/something" component={RenderNumber} extraProps={{n: 5}}/>
// renders the number 5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.