如何在反应js中点击按钮调用函数?

How to call a function on button click in react js?

我需要在点击按钮时调用一个函数。 我的代码是:

    createButtonsArray(arr){
         return arr.arr.map((key,index) =>
         <input type='button' onClick={this.sayHello}/>
    )}

    sayHello() {
        alert('Hello!');
    }

现在,我得到一个错误:

Unhandled Rejection (TypeError): Cannot read property 'sayHello' of undefined

会是什么?

试试这个

class Comp {
  constructor() {
    this.sayHello = this.sayHello.bind(this);
    this.createButtonsArray = this.createButtonsArray.bind(this);
  }

  sayHello() {
    alert("Hello!");
  }
  createButtonsArray(arr) {
    return arr.arr.map((key, index) => (
      <input type="button" onClick={this.sayHello} />
    ));
  }
}

如果你想绑定这个

class Comp {
  sayHello = () => {
    alert("Hello!");
  }

  createButtonsArray = (arr) => {
    return arr.arr.map((key, index) => (
      <input type="button" onClick={this.sayHello} />
    ));
  }
}