上下文: 我正在渲染Web视图,并且导航按钮在顶部栏上。当按下导航后退按钮时,我发送事件。同样,使用前进按钮,它会触发一个事件。问题是当我按下后退按钮时,也会导致前进按钮触发。因此,在控制台上说:按下后退按钮,按下前进按钮。此行为仅发生在Android中,在ios中工作完美。我不确定我在Android方面缺少什么。 我的组件如下。
import _EventEmitter from 'EventEmitter'
const appEventEmitter = new _EventEmitter()
export { appEventEmitter }
import React, { Component } from 'react'
import {
StyleSheet,
ScrollView,
} from 'react-native'
import { connect } from 'react-redux'
import { WebView } from 'react-native-webview'
import { Linking } from 'react-native'
import Spinner from 'react-native-loading-spinner-overlay'
import { appEventEmitter } from 'src/common'
import { Icon } from 'react-native-elements'
const goBack = 'goBack'
const goForward = 'goForward'
class HomeComponent extends Component {
static navigationOptions = ({navigation}) => {
return {
headerRight:(
<Icon
iconStyle={styles.chevronColor}
name="chevron-right"
onPress={() => appEventEmitter.emit(goForward) }
size={40}
/>),
headerLeft:(
<Icon
iconStyle={styles.chevronColor}
name="chevron-left"
onPress={() => appEventEmitter.emit(goBack) } // This causes to fire back and forward events
size={40}
/>),
}
}
constructor(props) {
super(props);
this.state = {
webViewRef: "webViewRef",
visible: true,
}
}
componentDidMount () {
this.goBackListenerId = appEventEmitter.addListener(goBack, () => this.goBack())
this.goForwardListenerId = appEventEmitter.addListener(goForward, () => this.goForward())
}
componentWillUnmount () {
appEventEmitter.removeListener(this.goBackListenerId)
appEventEmitter.removeListener(this.goForwardListenerId)
}
goBack = () => {
console.log("BACK PRESSED")
this.refs[this.state.webViewRef].goBack();
}
goForward = () => {
console.log("Forward PRESSED")
this.refs[this.state.webViewRef].goForward();
}
hideSpinner() {
this.setState({ visible: false });
}
showSpinner() {
this.setState({ visible: true });
}
render() {
return (
<ScrollView contentContainerStyle={styles.scrollableContainer}>
<Spinner
visible={this.state.visible}
style={styles.spinnerColor}
/>
<WebView
source={{uri: BASE_URL}}
style={styles.container}
onLoadStart={() => this.showSpinner()}
onLoadEnd={() => this.hideSpinner()}
ref={this.state.webViewRef}
javaScriptEnabled={true}
domStorageEnabled={true}
geolocationEnabled={true}
cacheEnabled={true}
/>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
scrollableContainer: {
flex: 1,
},
spinnerColor: {
color: 'white'
},
navigationHeader: {
backgroundColor: colors.primary,
},
container: {
flex: 1,
},
chevronColor: {
color: 'white'
}
});
const Home = connect()(HomeComponent)
export { Home }