简体   繁体   English

React.JS组件类中的函数未定义错误

[英]Function not defined error in React.JS component class

I have written a react component with a constructor, methods, and render. 我写了一个带有构造函数,方法和渲染的react组件。 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. 当我注释掉方法并且只使用render和构造方法时,一切都很好,但是当我添加方法时,除非我在构造方法之后关闭整个类,否则第一个方法总是以未定义的形式出现。

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". 这不会编译,并给出错误“'isLetterInWord'未定义”。 If I remove this function, the error is thrown on fillWord instead. 如果我删除此功能,则会在fillWord上引发错误。 If I add a "}" after the constructor the methods are all defined but render throws an unexpected token error on the return line. 如果在构造函数之后添加“}”,则所有方法均已定义,但render在返回行上引发意外的令牌错误。 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. 在这里,您正在定义类属性,当前(我认为)是第3阶段的建议。 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 . 您可以使用Babel的class-properties-transform插件来添加对此语法的支持,如果您愿意的话。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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