简体   繁体   中英

UseState to control

I use a button to control the audio player mute but it makes the player default mute, I want that only mute when clicking.How to edit it

import React, { useState } from "react";
import ReactAudioPlayer from "react-audio-player";

const Test = () => {
  const [ismute, setOpen] = useState(false);
  return (
    <><div>
      <ReactAudioPlayer
        controls
        muted={ismute ? "false": "True"}
        src='https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'
        loop
        autoPlay
         />
    </div><button onClick={() => setOpen(!ismute)}>click me!</button>
    </>
  );
};

export default Test

If you are passing as string ,

muted={ismute ? "false": "True"}

since the initial value of the ismute is false as:

const [ismute, setMute] = useState(false);

then what you are going to pass as a prop is True or false which is truthy value which makes ismute as always mute

For state ismute, initially assign value true instead of false as below:

const [ismute, setOpen] = useState(true);

You should pass muted prop as either true or false . You are passing as a string

muted={ismute ? false: true }

代码沙盒演示 I've created a simulation for player

For state ismute, initially assign value true instead of false as below:

const [ismute, setOpen] = useState(true);

Another correction might be at component ReactAudioPlayer :

<ReactAudioPlayer
    controls
    muted={ismute}
    src='https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'
    loop
    autoPlay
     />

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