无法从React App中的另一个函数调用一个函数

时间:2019-04-02 10:04:19

标签: javascript reactjs

我试图从componentDidMount()调用一个函数,该函数会根据我按下的键来播放声音。但是,我不断收到此“ Uncaught TypeError:this.playSound不是一个函数 pen.js:63“。我在做什么错?在存在类似问题的线程中,用户会建议绑定一个函数,但是我已经在组件构造函数中做到了。

playSound()运作良好,因为在其他元素中我成功地成功调用了它。

constructor(props){
    super(props)
    this.state={
      buttons:['Q','W','E','A','S','D','Z','X','C'],
      lastSound:""
    }
    this.playSound = this.playSound.bind(this);
  }

  componentDidMount(){
    window.addEventListener('keydown', function(e) {this.playSound(e.key)});
  }

  playSound(soundId){
    document.getElementById("drum-sound-"+soundId).play();
    let buttonPlayed;
      bankOne.map((x)=>{
        if (x.keyTrigger==soundId){
          buttonPlayed=x.id;
        }
      }
    );
    this.setState({lastSound:buttonPlayed});
  }

如果我犯了一个真正愚蠢的错误,我深表歉意,因为我是React和JavaScript的新手。预先谢谢你!

0 个答案:

没有答案