Playing sound in reactjs

前端 未结 3 2014
梦毁少年i
梦毁少年i 2020-12-02 15:54
import React, { Component } from \'react\'
import { Button, Input, Icon,Dropdown,Card} from \'semantic-ui-react\'
import { Link } from \'react-router-dom\'
import $          


        
3条回答
  •  庸人自扰
    2020-12-02 16:09

    Uncaught TypeError: Cannot read property 'setState' of undefined

    The error occurs because of how the this keyword works in JavaScript. I think the Audio should play just fine if we solve that issue.

    If you do a console.log(this) inside play() you will see that this it is undefined and that's why it throws that error, since you are doing this.setState().Basically the value of this inside play() depends upon how that function is invoked.

    There are two common solutions with React:

    1. Using bind() to set the value of a function's this regardless of how it's called:
    constructor(props) {
      super(props);
      this.play() = this.play.bind(this);
    }
    
    1. Using arrow functions which don't provide their own this binding
    
    

    Now you will have access to this.setState and this.audio inside play(), and the same goes for pause().

提交回复
热议问题