每当我移动到应用程序中的下一个屏幕时,我想停止声音播放器。
const [shallPlay, setPlay] = useState(true);
useEffect(() =\> {
if (shallPlay) {
try {
SoundPlayer.playSoundFile("om_namo`your text`\_venkateshaya", ".mp3");
} catch (e) {
console.log(`cannot play the sound file`, e);
}
} else {
SoundPlayer.stop();
}
}, \[shallPlay\]);
\<TouchableOpacity
onPress={() => {
setPlay(!shallPlay);
}}
>
我是原生反应新手。找不到解决办法
您可以使用
useFocusEffect
从'@react-navigation/native'导入{useFocusEffect};
const [shallPlay, setPlay] = useState(true);
useEffect(() => {
if (shallPlay) {
try {
SoundPlayer.playSoundFile('om_namo_venkateshaya', '.mp3');
} catch (e) {
console.log('cannot play the sound file', e);
}
} else {
SoundPlayer.stop();
} }, [shallPlay]);
useFocusEffect(
React.useCallback(() => {
// This will run when the screen is focused
return () => {
// This will run when the screen is unfocused
// Stop the sound player when navigating away
SoundPlayer.stop();
};
}, []) );