猿问

将 onMouseEnter 和 onMouseLeave 事件添加到音乐播放器

我正在编写一个音乐播放器的应用程序,但我遇到了障碍。我正在尝试一种方法:


•当我将鼠标悬停在一首歌曲上时,它会显示一个“播放”按钮来代替歌曲编号。


•当前播放的歌曲显示一个“暂停”按钮代替歌曲编号。


•暂停的歌曲显示“播放”按钮代替歌曲编号。


我想在此方法中使用 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();

                 }  

            }


梦里花落0921
浏览 111回答 1
1回答

DIEA

在我在这里对您的代码进行的测试中,我添加了showPlayOnHover属性以将其声明为 false,以处理悬停时出现的按钮。添加了渲染或不渲染按钮的方法:handlePlayOnHover = (song) => {&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; showPlayOnHover: !this.state.showPlayOnHover,&nbsp; &nbsp; &nbsp; &nbsp; isPlaying: !this.state.isPlaying&nbsp; &nbsp; })&nbsp; &nbsp; this.handleSongClick(song)}歌曲渲染结构更新为:<tr&nbsp;&nbsp; &nbsp; className="song" key={index}&nbsp;&nbsp; &nbsp; onClick={() => this.handleSongClick(song)}&nbsp; &nbsp; onMouseOver={() => this.handleOnHover(song)}&nbsp; &nbsp; onMouseOut={() => this.handleOnHover(song)}>&nbsp; &nbsp; &nbsp; <td className="song-actions">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span className="song-number">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {!this.state.showPlayOnHover ? index+1 : <span className="ion-play"></span>}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span className="ion-play"></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span className="ion-pause"></span>&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; <td className="song-title">{song.title}</td>&nbsp; &nbsp; &nbsp; <td className="song-duration">{song.duration}</td></tr>方法handleOnHover负责有条件地显示悬停时的播放按钮和悬停时的歌曲编号。
随时随地看视频慕课网APP

相关分类

Java
我要回答