React JS Uncaught Reference Error:函数未定义

jan*_*rea 11 javascript reactjs

我试图在ReactJs组件中的click事件时调用shuffleCards.但是,我收到以下错误:

Uncaught ReferenceError: shuffleCards is not defined
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

constructor(props) {
    super(props);

    this.state = {
        count: 0
    };
}

shuffleCards(array) {
    var i = array.length,
        j = 0,
        temp;

    while (i--) {
        j = Math.floor(Math.random() * (i+1));

        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

handleClickEvent(event) {
    var cards = [
        {txt: "A",
        isDisplayed: false},
        {txt: "B",
        isDisplayed: false},
        {txt: "C",
        isDisplayed: false}
    ];
    if (this.state.count == 0) {
        cards = shuffleCards(cards);
    }

}
Run Code Online (Sandbox Code Playgroud)

nem*_*035 27

编辑刚刚看到评论,并且zerkms已经为您提供了解决方案.我会留下我的答案以澄清澄清.


你的问题在于handleClickMethod,你在呼唤shuffleCards而不是this.shuffleCards

shuffleCards(array) {
  // ...
}

handleClickEvent(event) {
    // ...
    if (this.state.count == 0) {
        cards = this.shuffleCards(cards); // here you should use `this.`
    }
}
Run Code Online (Sandbox Code Playgroud)

原因是因为shuffleCards方法是在您的组件上定义的,可以通过this属性从其方法访问该方法.

如果您shuffleCards在其中定义handleClickMethod,则可以在不访问的情况下调用它this:

handleClickEvent(event) {

    function shuffleCards(array) {
      // ...
    }

    // ...
    if (this.state.count == 0) {
        cards = shuffleCards(cards); // here you don't need `this.`
    }
}
Run Code Online (Sandbox Code Playgroud)


Pio*_*cki 6

这对你有用吗?演示在这里:http : //codepen.io/PiotrBerebecki/pen/qaRdgX

您在方法中this提到时错过shuffleCardshandleClickEvent

shuffleCards(array) {
  // logic here
}

handleClickEvent(event) {
  cards = this.shuffleCards(cards);
}

render() {
  return (
    <button onClick={this.handleClickEvent.bind(this)}>Click me</button>
  );
}
Run Code Online (Sandbox Code Playgroud)