首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过withRouter指定注入属性的类型(typeScript)?

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

Stack Overflow用户
提问于 2019-05-06 18:46:08
回答 1查看 547关注 0票数 0

我对TypeScript非常陌生,我正在尝试创建一个封装在"withRouter“组中的组件(通过npm-package react-router-dom)来接收诸如匹配、历史和位置等属性。如何正确地做到这一点呢?我可以从@types/react-router-dom导入现成的界面吗?下面是我的第一次尝试:

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-06 22:42:54

只需从lib导入这些属性类型

代码语言:javascript
复制
import { RouteComponentProps, withRouter } from 'react-router-dom';

然后你不得不说你的组件有这些道具

代码语言:javascript
复制
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);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56003609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档