与 Typescript 反应:“历史”类型上不存在“推送”属性

gfe*_*els 10 javascript routing typescript reactjs react-router

我试图通过推入历史对象来远离视图。但是,当我尝试将路由推入其中时,我收到一条错误消息:

“历史”类型不存在“推送”属性。

  render(){
    return (
        <div className="loginWrapper">
    withRouter(({history}) => (<button onClick={()=>{history.push('/home')}} className="btn btn-primary">Pieteikties</button>))
  </div>
    )  
}
Run Code Online (Sandbox Code Playgroud)

我能做些什么来解决这个问题?

编辑:

我也试过这个:

logIn(){
  this.props.history.push('/new-location')
}
Run Code Online (Sandbox Code Playgroud)

使用这样的组件:

 render(){
    return (
        <div className="loginWrapper">
<button onClick={this.logIn} className="btn btn-primary">Pieteikties</button>
</div>
    )  
}
Run Code Online (Sandbox Code Playgroud)

它没有用。

Ern*_*sto 21

更新:我找到了一种新方法来做这种事情。与 b4 相同,您需要安装它们类型:

1.- npm i react-router react-router-dom

2.- npm i -D @types/react-router @types/react-router-dom

import React from "react";
import { RouteComponentProps } from "react-router-dom";

interface MyComponentProps extends RouteComponentProps {
 someOfYourOwnProps: any;
 someMorePropsIfNeedIt: any;
}

interface MyComponentState {
  someProperty: any;
  another: any;
}

export class MyComponent extends React.Component<MyComponentProps, MyComponentState> {

    public state: MyComponentState;
    public constructor (props: MyComponentProps) {
        super(props);

        this.state = {
            someProperty: "",
            another: ""
        }
    }

    public onClickHandler (evt: React.MouseEvent<HTMLButtonElement, MouseEvent>): void {
        evt.preventDefault();
    }

    public componentDidMount () {
        this.props.history;
    }
   public render (): React.ReactElement<MyComponentProps> {
        return (
            <div>trol</div>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

hihitl 我知道发生了什么。希望你仍然需要它。

1.- npm i react-router react-router-dom

2.- npm i -D @types/react-router @types/react-router-dom

import React from "react";
import { History, LocationState } from "history";

interface MyComponentProps {
 someOfYourOwnProps: any;
 history: History<LocationState>;
 someMorePropsIfNeedIt: any;
}
Run Code Online (Sandbox Code Playgroud)

然后在你的组件上,如果它是一个类做

class MyComponent extends Component<MyComponentProps, {}> {}
Run Code Online (Sandbox Code Playgroud)

如果是函数式

const MyComponent = (props: MyComponentProps) => {}
Run Code Online (Sandbox Code Playgroud)

  • 对于我的 cra typescript 应用程序,导入 { History, LocationState } from "history"; 和历史:History&lt;LocationState&gt;;正是我所需要的。谢谢! (2认同)

Håk*_*Lid 7

history在这里定义在哪里?有一个全球性window.history的网络标准。如果您想使用react-router history,它将作为道具传递。试试吧props.history.push()

该组件必须history从反应路由器接收道具。因此Route,例如,它应该是组件的直接子级,或者您必须通过其父级传递 props。