react-native - 使用返回时 NavigationEvents 不起作用
问题描述
我正在构建一个小型声音播放器页面。我正在使用 expo-av 库。当用户前进 {NavigationEvents onWillBlur } 正在工作并且当他后退时它没有执行时,我注意到了。
我需要达到的是:1)当用户向后或向前离开页面时停止声音播放。2)如果用户按两次播放,声音将被播放两次,所以如果它已经在运行,我不希望它再次播放
如果可以使用任何其他库来代替 expo-av ?
import React, {useState} from 'react';
import {View, Text, Button, StyleSheet, TouchableOpacity } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import { Audio } from 'expo-av';
import {AntDesign, Entypo} from '@expo/vector-icons';
const PlaySound = ({link}) => {
const [error, setError] = useState('')
const soundObject = new Audio.Sound();
const mySound = async () => {
try {
await soundObject.loadAsync({ uri : link });
await soundObject.playAsync();
} catch (err) {
setError('Wait while uploading your sound');
}
}
const stopSound = async () => {
try {
await soundObject.stopAsync(mySound);
} catch (error) {
setError('You must Play Sound First')
}
}
const pause = async () => {
try {
await soundObject.pauseAsync(mySound);
} catch (error) {
setError('Something went wrong !!! Please try again');
}
}
return (
<View>
<NavigationEvents onWillBlur = {stopSound} />
<Text>Play Sound</Text>
<View style = {styles.row}>
<TouchableOpacity
onPress = {mySound}>
<AntDesign name = 'caretright' size = {25} />
</TouchableOpacity>
<TouchableOpacity
onPress = {stopSound} >
<Entypo name = 'controller-stop' size = {25}/>
</TouchableOpacity>
<TouchableOpacity
onPress = {pause}>
<AntDesign name = 'pause' size = {25} />
</TouchableOpacity>
</View>
{error ? <Text>{error} </Text> : null }
</View>
);
};
const styles = StyleSheet.create({
row : {
flexDirection : 'row',
justifyContent : 'space-between',
marginVertical : 10
}
});
export default PlaySound;
解决方案
对于问题 1,当用户离开页面时您必须停止播放器。您可以使用 useEffect 挂钩。会是这样的,
useEffect(() => {
return () => {
stopSound();
}
}, []);
所以在上面的 useEffect 钩子中,返回的函数将在组件从屏幕上卸载(向前或向后)时运行。
对于第二个问题,您必须禁用播放按钮以避免多次点击。您可以使用useState
钩子创建一个状态并使其false
在播放按钮单击上并传递此 playButtonState 以禁用播放按钮可触摸不透明度的道具。
我希望你现在清楚了。
推荐阅读
- php - 尝试发布 Web 服务器 PHP,多个参数不起作用 VB
- javascript - 在一个需要
工作的功能,而不是 重定向网址 我面临一个问题
<table>
我有一个表行,它有一个重定向 URL,只有一个表数据
<td>
具有不同的功能<table> <thead> <th></th> <
- java - InstanceNotFoundException:AWS EC2 实例上的 jboss.as:subsystem=security,security-domain 零星错误
- java - Springboot更新后RestService中的重试不起作用
- c++ - 在 main 中返回一个函数
- javascript - react-grid-layout:网格单元是如何计算的?
- winforms - 父级的前景色不适用于组框文本和组合框
- android - 如何在 android studio 项目中使用 Sketch 设计
- python - 将字符串格式的不同日期格式解析为日期格式pyspark when 子句
- amazon-web-services - 使用命令行从 AWS 成本和使用报告中获取资源 ID