P
P
Paxest2019-04-11 12:08:47
React
Paxest, 2019-04-11 12:08:47

Why doesn't sound play when a key is pressed?

Good day!
When you press any key on the keyboard, the sound is played, if you use Audio in the justAdd function, if Audio is in another function and place a link to this function, then the melody does not play.
Please explain the processes, because for me, these two functions are equivalent, but if it works in one case and not in the other, then these are completely different things ..

class App extends React.Component {
    componentDidMount() {
    document.addEventListener('keydown', this.justAdd);
  }
  componentWillUnmount() {
    document.removeEventListener('keydown', this.justAdd);
  }
justAdd() {
   // если задействовать sound то мелодия проигрывается при нажатии на клавиши клавиатуры
   // const sound = new Audio("https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3");
   //  sound.play();

  // если задействовать функцию playMusic с идентичным кодом, то нажатия не работают
  //this.playMusic();
  }
  
  playMusic() {
   const sound = new Audio("https://s3.amazonaws.com/freecodecamp/drums/Chord_3.mp3");
   sound.play();
  }
  
  render() {
    return (
    <div>Музыку! </div>
    
    )
  }
}
React.render(<App />, document.getElementById("app"));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2019-04-11
@Paxest

The context is lost.
https://developer.mozilla.org/en-US/docs/Web/JavaS...
https://reactjs.org/docs/faq-functions.html
You can either make a bound arrow function (requires babel plugin, works from boxes if you have create-react-app) or bind in the constructor.

class App extends React.Component {
  constructor(props) {
    super(props);

    this.justAdd = this.justAdd.bind(this);
  }

  justAdd() {
    // your logic
  }
}

class App extends React.Component {
  // option 2
  justAdd = () => {
    // your logic, 
  };
}

A
Anton Spirin, 2019-04-11
@rockon404

When passing the justAdd method to the listener, the context is lost. A good solution would be to use an arrow function instead of a method:

justAdd = () => {
  this.playMusic();
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question