首页 > 解决方案 > 与打字稿反应:“历史”类型上不存在属性“推送”

问题描述

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

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

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

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

编辑:

我也试过这个:

logIn(){
  this.props.history.push('/new-location')
}

使用这样的组件:

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

它没有用。

标签: javascriptreactjstypescriptroutingreact-router

解决方案


更新:我找到了一种新方法来做这种事情。与 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>
        )
    }
}

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;
}

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

class MyComponent extends Component<MyComponentProps, {}> {}

如果它是功能性的

const MyComponent = (props: MyComponentProps) => {}

推荐阅读