在一個(gè)component里面加上對(duì)返回鍵的監(jiān)聽(tīng),但是如果有一個(gè)新的screen push過(guò)來(lái)桥言,返回鍵的監(jiān)聽(tīng)依舊存在,所以需要在頁(yè)面切換的時(shí)候葵礼,對(duì)監(jiān)聽(tīng)進(jìn)行注銷與重新注冊(cè)号阿。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.didFocusSubscription = props.navigation.addListener('didFocus', () => {
BackHandler.addEventListener('hardwareBackPress', this.backPress);
});
}
componentDidMount() {
this._willBlurSubscription = this.props.navigation.addListener('willBlur', () => {
BackHandler.removeEventListener('hardwareBackPress', this.backPress);
});
}
componentWillUnmount() {
if (this.didFocusSubscription) this.didFocusSubscription.remove();
if (this._willBlurSubscription) this._willBlurSubscription.remove();
}
}