web-dev-qa-db-fra.com

React TypeScript HoC - en passant Component comme prop

Suite à ce tutoriel: https://reacttraining.com/react-router/web/example/auth-workflow .

Essayer de reproduire le code:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      fakeAuth.isAuthenticated ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{
            pathname: "/login",
            state: { from: props.location }
          }}
        />
      )
    }
  />
);

En TypeScript:

import * as React from 'react';
import { Route, RouterProps } from 'react-router';

interface Props extends RouterProps {
  component: React.Component;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
  return (
    <Route
      {...rest}
      render={(props) => <Component {...props} />}
    />
  );
};

export default PrivateRoute;

Mais cela échouerait toujours. J'ai essayé différentes variations. Celui que j'ai publié le plus récent. Obtenir:

enter image description here

Il me semble que je dois passer Generic pour le type Component, mais je ne sais pas comment.

MODIFIER:

La solution la plus proche à ce jour:

interface Props extends RouteProps {
  component: () => any;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
  return (
    <Route
      {...rest}
      render={(props) => <Component {...props} />}
    />
  );
};

Puis:

<PrivateRoute component={Foo} path="/foo" />
11
0leg

Vous voulez passer un constructeur de composant, pas une instance de composant:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

interface Props extends RouteProps {
    component: new (props: any) => React.Component;
}

const PrivateRoute = ({ component: Component, ...rest }: Props) => {
    return (
        <Route
            {...rest}
            render={(props) => <Component {...props} />}
        />
    );
};

export default PrivateRoute;

class Foo extends React.Component {

}
let r = <PrivateRoute component={Foo} path="/foo" />

Modifier

Une solution plus complète devrait être générique et utiliser RouteProps à la place RouterProps:

import * as React from 'react';
import { Route, RouteProps } from 'react-router';

type Props<P> =  RouteProps & P & {
    component: new (props: P) => React.Component<P>;
}

const PrivateRoute = function <P>(p: Props<P>) {
    // We can't use destructureing syntax, because : "Rest types may only be created from object types", so we do it manually.
    let rest = omit(p, "component");
    let Component = p.component;
    return (
        <Route
            {...rest}
            render={(props: P) => <p.component {...props} />}
        />
    );
};

// Helpers
type Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T];  
type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>; 
function omit<T, TKey extends keyof T>(value:T, ... toRemove: TKey[]): Omit<T, TKey>{
    var result = Object.assign({}, value);
    for(let key of toRemove){
        delete result[key];
    }
    return result;
}


export default PrivateRoute;

class Foo extends React.Component<{ prop: number }>{

}
let r = <PrivateRoute component={Foo} path="/foo" prop={10} />

Après quelques heures et quelques recherches, voici la solution qui correspond à mes besoins:

import * as React from 'react';
import { Route, RouteComponentProps, RouteProps } from 'react-router';

const PrivateRoute: React.SFC<RouteProps> =
  ({ component: Component, ...rest }) => {
    if (!Component) {
      return null;
    }
    return (
      <Route
        {...rest}
        render={(props: RouteComponentProps<{}>) => <Component {...props} />}
      />
    );
  };

export default PrivateRoute;

  • Non any;
  • Pas de complexité supplémentaire;
  • Modèle de composition conservé;
2
0leg