简体   繁体   中英

Function not defined error in React.JS component class

I have written a react component with a constructor, methods, and render. When I comment out the methods and have only the render and constructor everything is fine, but when I add the methods the first always comes up as undefined unless I close off the whole class after the constructor.

Here is my class (since it doesn't matter what is in the methods I just put the declarations for brevity):

export default class App extends Component {

  constructor(props) {
    super(props);
    const allWords = ["word", "pipe", "dear", "deer", "fish", "coat"];
    const word= allWords[Math.floor(Math.random()*allWords.length)];
    var lettersFound = [];
    for (var i=0; i<word.length;i++) {
      lettersFound = [...lettersFound, [i, "_"]];
    }
    this.fillWord = this.fillWord.bind(this);

    this.state = {
      word: word,
      numWrongGuesses: 0,
      lettersGuessed: [],
      lettersFound: lettersFound,
      error: ""
    }
  }

  isLetterInWord = (letter) => {
  }

  fillWord = () => {
  }



  handleGuess = (letter) => {
  }

  render () {
    return (
      <div className="App">
      </div>
    );
  }

}

This doesn't compile, giving the error "'isLetterInWord' is not defined". If I remove this function, the error is thrown on fillWord instead. If I add a "}" after the constructor the methods are all defined but render throws an unexpected token error on the return line. I do not understand why I would want to close off the class after the constructor, or why it isn't compiling as is.

Here you are defining class properties, which is currently (I think) is stage-3 proposal. In other words it is not supported by default. May be because of this you are getting errors. You can use class-properties-transform plugin for Babel to add support of this syntax though if you want to .

isLetterInWord = (letter) => {
  }

  fillWord = () => {

  }

Try defining methods as and see if it works

isLetterInWord(letter) {

}

Try to bind the function inside the constructor like this:

this.isLetterInWord = this.isLetterInWord.bind(this);
this.fillWord = this.fillWord.bind(this)
this.handleGuess = this.handleGuess.bind(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM