gpt4 book ai didi

javascript - react 处理映射数组中每个项目的单独音频问题

转载 作者:行者123 更新时间:2023-11-30 20:58:11 25 4
gpt4 key购买 nike

每次用户点击在数组上映射后创建的 li 元素时,我都会尝试播放 audio 文件。

在我的 React 类中,我传入一个(称为 songs)对象数组作为 props,如下所示:

const songs = [{
name: 'Oasis',
url: 'oasis.mp3'
},
{
name: 'Blur',
url: 'blur.mp3'
},
{
name: 'U2',
url: 'u2.mp3'
},
];

我遇到的问题是音频一直在播放上一首轨道。我知道这是因为对 audio 的引用在每个 li 实例中都是不同的,因为我已映射到数组上。我想要对 audio 进行相同的引用,这样我就可以确保一次只播放一个 audio 文件。我还有一个 prop 来确定当前是否正在播放 audio 文件。

有谁知道如何克服这个问题吗?

class Audio extends Component {

render() {

this.props.songs.map(song => {

let audio;

const playSong = () => {

if(!this.props.audioPlaying){
audio = new Audio(song.url);
audio.play();
} else {
audio.pause();
audio = new Audio(song.url);
audio.play();
}
}

return (
<li onClick={ playSong }>Play { song.name }</li>
);
};

};

最佳答案

你应该这样试试

class Audio extends Component {

static audio;

playSong = (song) => {
if(!this.props.audioPlaying){
this.audio = new Audio(song.url);
this.audio.play();
} else {
this.audio.pause();
this.audio = new Audio(song.url);
this.audio.play();
}
}

render() {
this.props.songs.map(song => {
return (
<li onClick={(song) => this.playSong(song)}>Play { song.name }</li>
);
});
}
};

关于javascript - react 处理映射数组中每个项目的单独音频问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47427990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com