如何通过withRouter在注入的属性上指定类型(typeScript)?

时间:2019-05-06 10:46:08

标签: reactjs typescript interface react-router

我对TypeScript还是很陌生,我正在尝试创建一个包装在“ withRouter” HOC中的组件(通过npm-package react-router-dom),以接收诸如比赛,历史记录和位置之类的道具。如何正确地做到这一点?我可以从@types/react-router-dom导入现成的界面吗?以下是我的第一次尝试:

import classes from './SomeComponent.module.scss';
import { withRouter } from 'react-router-dom';

interface SomeComponentProps {}

interface WithRouter {
  match: ObjectWithAnyKeys;
  location: ObjectWithAnyKeys;
  history: ObjectWithAnyKeys;
}

interface ObjectWithAnyKeys {
  [s: string]: string;
}

export const SomeComponent: React.FunctionComponent<SomeComponentProps & WithRouter> = ({
  match,
  location,
  history,
}) => {
  return (
    <div className={classes.ReadActivityContainer}>
      {'Some component that uses the router props match, location and history'}
    </div>
  );
};

export default withRouter(SomeComponent as any);

1 个答案:

答案 0 :(得分:1)

只需从lib导入这些道具类型

import { RouteComponentProps, withRouter } from 'react-router-dom';

比您不得不说您的组件具有这些道具

type ownProps = {}
export const SomeComponent: React.FunctionComponent<ownProps & RouteComponentProps> = (props: ownProps & RouteComponentProps) => {
  const history = props.history;
  const match = props.match;
  // ect... all in props
  return (
    <div>
      some component that uses the router props match, location and history
    </div>
  );
};

export default withRouter(SomeComponent);