简体   繁体   中英

play sound if condition is true in reactjs

I'm trying to play sound if the condition is correct but it's not working. I tried putting the sound in button it works. Here's my code

import playalert from '../src/alert.wav';

function App() {
  const [play, { stop }] = useSound(playalert);

  //some code
  if (value > 14){
    play();
  }
}

I think you need to return the jsx element and put your condition into funciton something like this

 const handleClick = () => {
    if(condition) {
     play();
 
    }
    
  };

  return (
    <Button onClick={handleClick}>
      <span role="img" aria-label="Person with lines near mouth">
        🗣
      </span>
    </Button>
  );

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