我想在带有打字稿的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
});
答案 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
});