反应-单击按钮

时间:2019-07-12 21:54:27

标签: react-redux

我希望能够单击一个按钮并导航到站点上的另一个页面。

我尝试使用此页面中的代码,但无法使其适合我的代码。我也从另一页获得了此代码。

任何帮助表示赞赏。

React route example

import React from 'react';

class Home extends React.Component{
    constuctor() {
        this.routeChange = this.routeChange.bind(this);
      }

    routeChange() {
        let path = '/CreateAccount';
        this.props.history.push(path);
      }      

    render(){
        return(

          <div>
          <p>
                <button         
                onClick={this.routeChange}
                class="btn btn-lg btn-gradient"
                >
                    Signup                        
                </button></p>
          </div>
            )
          }
    }

1 个答案:

答案 0 :(得分:0)

您需要将函数绑定到正确的this。最简单的方法是对routeChange使用ES6箭头功能。如果不这样做,则routeChange中的this是点击的发起者,而不是组件。

箭头功能自动绑定到包含实例的this

routeChange = ()=> {
    let path = '/CreateAccount';
    this.props.history.push(path);
  }  

还有其他方法可以解决此问题,例如在构造函数中对其进行修补:

constructor( props ){
    super( props );
    this.routeChange = this.routeChange.bind(this);
  }

...但是箭头功能比imo更简单,更方便。