更改React组件中的声音

时间:2019-05-08 07:18:37

标签: reactjs typescript html5-audio

我想在带有打字稿的react app中在后台播放音乐,但是在父级更改音乐时,子节点上的声音没有任何变化。

import React from 'react';
import './audioPlayer.css';

interface AudioPlayerProps {
  music: string
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({ music }) => {

  return (
    <audio >
      <source src={music} type="audio/mpeg" />
      Your browser does not support the audio tag.
    </audio>
  );
};

export default React.memo(AudioPlayer,(prevProps, nextProps)=>{
  return prevProps.music === nextProps.music
});

1 个答案:

答案 0 :(得分:0)

使用ref JSX属性解决问题

import React, { useState, useEffect } from 'react';
import './audioPlayer.css';

interface AudioPlayerProps {
  music: string,
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({ music}) => {

  const [audio, setAudio] = useState();

  useEffect(() => {
    if(audio){
       audio.pause();
       audio.load();
       audio.play();
    }
  }, [music,audio]);

  return (
    <audio ref={(audioref)=>{ setAudio(audioref) }} >
      <source src={music} type="audio/mpeg" />
      Your browser does not support the audio tag.
    </audio>
  );
};

export default React.memo(AudioPlayer,(prevProps, nextProps)=>{
  return prevProps.music === nextProps.music
});