我对TypeScript非常陌生,我正在尝试创建一个封装在"withRouter“组中的组件(通过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);发布于 2019-05-06 22:42:54
只需从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);https://stackoverflow.com/questions/56003609
复制相似问题