Reactjs 如何在React with TypeScript中更改提交事件的路由

Reactjs 如何在React with TypeScript中更改提交事件的路由,reactjs,typescript,Reactjs,Typescript,我使用React with TypeScript,我只想在单击submit按钮时,将路由更改为特定状态 this.props.router.push('/list')不使用提交方法 反应版本: "react": "15.5.4", "react-dom": "15.5.4", 我在tsx文件中的代码 import * as React from 'react'; import { BrowserRouter } from 'react-router-dom'; export interfac

我使用React with TypeScript,我只想在单击submit按钮时,将路由更改为特定状态

this.props.router.push('/list')不使用提交方法

反应版本:

"react": "15.5.4",
"react-dom": "15.5.4",
我在tsx文件中的代码

import * as React from 'react';
import { BrowserRouter } from 'react-router-dom';

export interface CreateProps {
    router?: BrowserRouter;
}

export class Create extends React.Component<CreateProps, {}> {

    constructor(props: CreateProps) {

        super(props);
    }

    public render() {
        return <div>
            <h1>Create</h1>
            <form className="WelcomeForm">
                <input name="Date" />
                <button onClick={() => { this.submit() }}>Save</button>
            </form>
        </div>;
    }

    submit() {
        this.props.router.push('/list');
    }
}
import*as React from'React';
从“react router dom”导入{BrowserRouter};
导出接口CreateProps{
路由器?:浏览器路由器;
}
导出类Create.Component{
构造函数(props:CreateProps){
超级(道具);
}
公共渲染(){
返回
创造
{this.submit()}>保存
;
}
提交(){
this.props.router.push('/list');
}
}

您可以通过道具访问以下对象:

  • 历史记录
  • 位置
  • 匹配
资料来源:

在您的情况下,您应该使用对象来更改路径,而不是路由器,因为这样的道具不存在

this.props.history.push('/list');

我使用了您建议的代码,但抛出了以下错误TS2339:类型“Readonly&Readonly”上不存在属性“history”,因此这意味着传递给
的不是该组件。您必须使用
react router dom
中的
withRouter
函数包装您的
类Create…
代码。您可以在官方react router文档中看到示例代码,而此代码可能会回答此问题,并提供有关此代码为什么和/或如何回答此问题的附加上下文,以提高其长期价值。
  contextTypes: {
    router: React.PropTypes.object
  }


  submit(event) {
    this.context.router.push('/list')
  }