添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Home TypeScript Crash Course

React Router

withRouter

To use a component injected with withRouter props, import and use RouteComponentProps ( declaration ) from react-router :

import { RouteComponentProps, withRouter } from 'react-router';
type SomeComponentProps = RouteComponentProps;
const SomeComponent: React.FC<SomeComponentProps> = ({ history }) => {
const goHome = () => history.push('/home');
return <button onClick={goHome}>Go Home</button>;
};
export default withRouter(SomeComponent);

URL Parameters

To type URL parameters, import and use RouteComponentProps ( declaration ) from react-router . Pass your parameter definitions as a type variable to RouteComponentProps :

// Router.tsx
import { BrowserRouter, Route } from 'react-router-dom';
const Router = () => {
return (
<BrowserRouter>
<Route exact path="/books/:id" component={Books} />
</BrowserRouter>
);
};
// BookDetail.tsx
import { RouteComponentProps, withRouter } from 'react-router';
type BookDetailParams = {
id: string; // parameters will always be a string (even if they are numerical)
};
type BookDetailProps = RouteComponentProps<BookDetailParams>;
const BookDetail: React.FC<> = ({ match }) => {
return <div>Book ID: {match.params.id}</div>;
};
export default withRouter(BookDetail);