reactjs - 当我按下主屏幕按钮反应原生时如何调用函数
问题描述
我有一个声音播放器应用程序,我希望它在用户按下 android 中的主屏幕按钮时停止播放当前歌曲,实际上在按下主屏幕时正在播放声音。
我使用componentWillUnmount
后退按钮,但对于主屏幕按钮我不知道应该使用什么?
解决方案
您需要使用AppState来帮助您找到您的应用程序处于哪个状态。当 State 为背景时,您可以执行您的逻辑
这是示例代码:
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
应用状态
active - The app is running in the foreground
background - The app is running in the background. The user is either:
in another app
on the home screen
[Android] on another Activity (even if it was launched by your app)
inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call
推荐阅读
- sql - 如何使用 Microsoft SQL CONTAINS 搜索列中任意位置包含单词的行,类似于 LIKE '%word%'?
- netsuite - NetSuite 或 SuiteScript 按项目筛选子列表中的供应商
- java - VSCode maven proj包org.springframework.boot.SpringApplication不存在
- php - 如何在wordpress的用户名中转义斜杠('/')?
- r - R中向量的指数移动平均值
- swift - 如何在 SwiftUI 中访问另一个 CoordinateSpace 的 safeAreaInsets
- python - 我怎样才能摆脱这些 seaborn 弃用警告并仍然获得完全相同的数字?
- ios - 应用程序未在 iOS 文件浏览器中显示为顶级应用程序
- github - 我的 git push 不工作,给出错误:RPC 失败;curl 18 传输已关闭,剩余未完成的读取数据
- reactjs - 如何使用 react-jsonschema-forms 创建一个典型的国家/省(或州)依赖项下拉列表?