我正在尝试学习如何创建一个单例实例,该实例包含一个值,该值随后将在某个组件的状态下使用。例如,假设我要创建一个AudioControl组件,其中包含一个播放/暂停,它将更改应用程序是否在播放音乐的状态。现在还要说,我们正在使用将组件嵌入到其中的多个屏幕。尽管每个屏幕都将包含其自己的AudioControl实例,但我希望此组件的state.playing来自存储此值的单例类。
我有工作,但只有一半。如果我运行该应用程序(按播放,然后转到下一个屏幕以查看该AudioControl组件是否也发生了更改,则可以。但是,如果我运行该应用程序,然后在按播放按钮之前切换选项卡,然后在另一个屏幕上按播放不会更改其他音频组件的状态。
这是我到目前为止所拥有的。我也研究过依赖注入,但是我是所有这些的新手,并且想了解这两种方法。
我的代码(App.js):
import React, { Component } from "react";
import { View, Text, Button} from "react-native";
import { createBottomTabNavigator, createAppContainer } from "react-navigation";
class AudioManager {
static _instance;
playing = false;
static getInstance = () => {
if (AudioManager._instance == null) {
AudioManager._instance = new AudioManager()
}
return this._instance;
}
}
let commonAudioManager = AudioManager.getInstance()
class AudioControls extends Component {
constructor(props) {
super(props)
this.state = {
playing: commonAudioManager.playing
}
}
play = () => {
commonAudioManager.playing = true
this.setState({
playing: commonAudioManager.playing
})
}
pause = () => {
commonAudioManager.playing = false
this.setState({
playing: commonAudioManager.playing
})
}
render() {
return (
<View>
<Text>Playing: {this.state.playing ? "Yes" : "No"}</Text>
{ this.state.playing ? <Button title="Pause" onPress={this.pause} /> : <Button title="Play" onPress={this.play} /> }
</View>
)
}
}
class HomeScreen extends Component {
static navigationOptions = {
title: "Home"
}
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center"}}>
<AudioControls />
</View>
)
}
}
class AudioScreen extends Component {
static navigationOptions = {
title: "Audio"
}
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center"}}>
<AudioControls />
</View>
)
}
}
const navigatorStack = createBottomTabNavigator({
Home: HomeScreen,
Audio: AudioScreen
})
export default createAppContainer(navigatorStack)