我正在獲取一堆曲目,每首曲目都有自己的按鈕來播放每首曲目。我可以點擊它們播放,然后再次點擊暫停音頻,但如果我嘗試播放新音頻而不暫停當(dāng)前正在播放的音頻,除非我雙擊它,否則它不會播放,因為 isPlaying 狀態(tài)將設(shè)置為 false(這是我切換播放/暫停的方式)。我希望能夠在 isPlaying 為 true 時單擊新音頻,而不是將該狀態(tài)更改為 false(但如果我單擊同一個按鈕兩次仍然能夠暫停當(dāng)前音頻)。謝謝!const App = () => { const [tracks, setTracks] = React.useState(null); const [currentSong, setCurrentSong] = useState(null); const [currentId, setCurrentId] = useState(null); const [isPlaying, setIsPlaying] = useState(false); const audio = useRef(); // toggle function for toggling whether audio is played or paused const togglePlay = () => { setIsPlaying(!isPlaying); }; // onClick function for handling currentSong and isPlaying state const handleClickPlay = (track) => { setCurrentSong(track); setCurretId(track.id); setIsPlaying(true); if (isPlaying) { togglePlay(); } }; React.useEffect(() => { if (currentSong) { if (isPlaying) { audio.current.play(); } else { audio.current.pause(); } } }, [currentSong, isPlaying]); React.useEffect(() => { if (isPlaying) { if (setCurrentSong) { setIsPlaying(true); } } }, []); React.useEffect(() => { fetch("/album.json") .then((response) => response.json()) .then((data) => { const tracks = Object.values(data.entities.tracks); setTracks(tracks); }); }, []); if (!tracks) { return <div>Loading...</div>; } console.log(currentSong); console.log(currentId); console.log(isPlaying); return ( <div> {currentSong && ( <audio src={currentSong.stems.full.lqMp3Url} ref={audio}></audio> )} <table> <tbody> {tracks.map((track) => ( <TrackRow track={track} handleClickPlay={handleClickPlay} isPlaying={isPlaying} id={currentId} currentSong={currentSong} trackMatchId={() => currentSong === currentId} /> ))} </tbody> </table> </div> );};
將音頻 isPlaying 狀態(tài)設(shè)置為對當(dāng)前音頻唯一
德瑪西亞99
2023-04-27 15:07:47