我正在编写一个音乐播放器应用程序,但是遇到了麻烦。我正在尝试一种方法:
•当我将鼠标悬停在歌曲上时,它会显示一个“播放”按钮来代替歌曲编号。
•当前正在播放的歌曲在歌曲编号的位置显示一个“暂停”按钮。
•暂停的歌曲显示一个“播放”按钮来代替歌曲编号。
我想在此方法中使用onMouseEnter和onMouseLeave事件,但我不知道从哪里开始
这是我的相册组件
import React, { Component } from 'react';
import albumData from './../data/albums';
class Album extends Component {
constructor(props) {
super(props);
const album = albumData.find( album => {
return album.slug === this.props.match.params.slug
});
this.state = {
album: album,
currentSong: album.songs[0],
isPlaying: false
};
this.audioElement = document.createElement('audio');
this.audioElement.src = album.songs[0].audioSrc;
}
play() {
this.audioElement.play();
this.setState({ isPlaying: true });
}
pause() {
this.audioElement.pause();
this.setState({ isPlaying: false });
}
setSong(song) {
this.audioElement.src = song.audioSrc;
this.setState({ currentSong: song });
}
handleSongClick(song) {
const isSameSong = this.state.currentSong === song;
if (this.state.isPlaying && isSameSong) {
this.pause();
} else {
if (!isSameSong) { this.setSong(song); }
this.play();
}
}
render() {
return (
<section className="album">
<section id="album-info">
<img id="album-cover-art" src={this.state.album.albumCover} alt={this.state.album.title}/>
<div className="album-details">
<h1 id="album-title">{this.state.album.title}</h1>
<h2 className="artist">{this.state.album.artist}</h2>
<div id="release-info">{this.state.album.releaseInfo}</div>
</div>
</section>
<table id="song-list">
<colgroup>
<col id="song-number-column" />
<col id="song-title-column" />
<col id="song-duration-column" />
</colgroup>
<tbody>
{this.state.album.songs.map( (song, index) =>
<tr className="song" key={index} onClick={() => this.handleSongClick(song)} >
<td className="song-actions">
<button>
<span className="song-number">{index+1}</span>
<span className="ion-play"></span>
<span className="ion-pause"></span>
</button>
</td>
<td className="song-title">{song.title}</td>
<td className="song-duration">{song.duration}</td>
</tr>
)}
</tbody>
</table>
</section>
);
}
}
export default Album;
答案 0 :(得分:0)
在对您的代码进行测试的过程中,我添加了 showPlayOnHover 属性以将其声明为false,以处理悬停时出现的按钮。
添加了呈现按钮的方法:
handlePlayOnHover = (song) => {
this.setState({
showPlayOnHover: !this.state.showPlayOnHover,
isPlaying: !this.state.isPlaying
})
this.handleSongClick(song)
}
并且歌曲渲染结构已更新为:
<tr
className="song" key={index}
onClick={() => this.handleSongClick(song)}
onMouseOver={() => this.handleOnHover(song)}
onMouseOut={() => this.handleOnHover(song)}
>
<td className="song-actions">
<button>
<span className="song-number">
{!this.state.showPlayOnHover ? index+1 : <span className="ion-play"></span>}
</span>
<span className="ion-play"></span>
<span className="ion-pause"></span>
</button>
</td>
<td className="song-title">{song.title}</td>
<td className="song-duration">{song.duration}</td>
</tr>
方法 handleOnHover 负责有条件地显示鼠标悬停时的播放按钮和歌曲悬停时的歌曲编号。