Jon*_*amb 5 typescript reactjs react-router-dom
我遇到了一个问题,其中我有一个无状态组件,它从 History 对象传递过来,react-router-dom并通过 props 将该对象传递给有状态对象。打字稿似乎不认为我可以将历史对象作为道具传递下去。
这是我的组件
import { History } from 'history';
import * as React from 'react';
import { RouteComponentProps, withRouter } from 'react-router-dom';
const SignInPage = ({ history }: { history: History }) =>
<div>
<h1>SignIn</h1>
<SignInForm history={history} />
</div>
class SignInForm extends React.Component<RouteComponentProps<{}>, {}> {
constructor(props: RouteComponentProps<{}>) {
super(props);
}
public handleClick = () => {
const { history } = this.props;
history.push('/home')
};
public render() {
return (
<button onClick={this.handleClick}>Sign In!</button>
);
}
}
export default withRouter(SignInPage);
export { SignInForm };
Run Code Online (Sandbox Code Playgroud)
我得到的错误是这个。
Type '{ history: History; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<SignInForm> & Readonly<{ children?: ReactNode; }> ...'.
Type '{ history: History; }' is not assignable to type 'Readonly<RouteComponentProps<{}, StaticContext>>'.
Property 'location' is missing in type '{ history: History; }'.
Run Code Online (Sandbox Code Playgroud)
我从未使用过 React Router,但如果我正确理解了类型,通过声明SignInForm extends React.Component<RouteComponentProps<{}>, {}>,你是说SignInForm需要路由组件在被 React Router 调用时通常接收到的所有道具。由于您自己调用它并仅传递历史记录,因此您应该将其声明为SignInForm extends React.Component<{history: History}, {}>.