首页 > 解决方案 > React - 单击按钮时无法读取未定义的属性“道具”

问题描述

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

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

任何帮助表示赞赏。

反应路线示例

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

标签: react-redux

解决方案


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

箭头函数会自动绑定到this包含实例的 。

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

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

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

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


推荐阅读