簡體   English   中英

將自定義道具傳遞給私有路由 - React Typescript

[英]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版本采用典型的RouteComponentPropsExtraProps (作為頂級道具)。

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

Typescript 游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM