Functionality of reverse processing

I would like to know the recommended method (if any) for processing the back button in the reaction-native mode when working with the Android platform.

I know that I can register listeners on the screen, but due to the fact that the navigation works, there is no clear flow for binding or canceling event listeners during navigation.

So far I have two ideas.

1) I can register one listener and make a handler decision based on my redux store. This means that if I have a screen where I have a popup that I want to close with the "Back" button, I have to open it in the repository. Essentially, anything in my application that I want to touch on the return button must be connected to the repository. Dirty

2) I can register the listener on the screen. From what I said earlier, there are no reliable lifecycle hooks available for this, so I will need to manually on my end. I always need to know what action will move around the new screen and unlock the listener on a particular screen before navigating.

This solves half the problem. When navigating the screen, it must reconnect the listener. You don’t know how to do this, except to mess with componentWillRecieveProps and others. Still seems dirty.

+6
source share
2 answers

react-navigation handles the basic functionality of the back button for you without any work.

, react-navigation-addons, 2 : focus blur, / , .

2) ​​ , . ​​ , . :

class Screen extends Component {
    handleBack = () => {
    ...
    }

    screenFocus = () => {
        // add back button listener or any other code you want to execute on screen focus
        BackHandler.addEventListener('hardwareBackPress', this.handleBack);
    }

    screenBlur = () => {
        // remove back button listener or add any other code you want to execute on screen blur
        BackHandler.removeEventListener('hardwareBackPress', this.handleBack);
    }

    componentDidMount() {
        this.props.navigation.addListener('focus', this.screenFocus);
        this.props.navigation.addListener('blur', this.screenBlur);
    }

    componentWillUnmount() {
        this.props.navigation.removeListener('focus', this.screenFocus);
        this.props.navigation.removeListener('blur', this.screenBlur);
    }
    ...
}
+3

React-native api Android AppleTV. eventListender BackHandler. Docs

react-navigation, , . , , leftButton onPress. :

const _RootContainer = (props) => {
  const navigation = addNavigationHelpers({
    dispatch: props.dispatch,
    state: props.nav,
  })
  BackHandler.addEventListener('hardwareBackPress', function() {
  const route = navigation.state.routes[navigation.state.index]
  const screen = stack[route].screen
  const navOptions = screen.navigationOptions({navigation})
      if (navOptions.headerLeft) {
    navOptions.headerLeft.props.onPress()
  }
      return true;
  });
  return (<View style={{ flex: 1 }}>
    <AppNavigator
      navigation={navigation}
    />
  </View>
)}
+1

All Articles