如何使用TypeScript在React中更改提交事件的路由

时间:2017-07-23 12:24:00

标签: reactjs typescript

我使用React和TypeScript,我只想在提交按钮点击时,将路由更改为特定状态。

this.props.router.push('/list');无法处理提交方法。

React版本:

"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');
    }
}

2 个答案:

答案 0 :(得分:0)

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

  • history
  • location
  • match

来源:Philosophy - react-router documentation

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

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

答案 1 :(得分:0)

  contextTypes: {
    router: React.PropTypes.object
  }


  submit(event) {
    this.context.router.push('/list')
  }
相关问题