简体   繁体   中英

How do I handle backAndroidHandler in each scene using react-native-router-flux

As the title description, I'm using react-native-router-flux.

And there is a question, I used backAndroidHandler={true} in <Router/> work normally before.

But now, because some reason I have to set backAndroidHandler to control physical back button enable in different scene.

So I can't just put it in router something like this before:

Example:

<Router
    backAndroidHandler={true}>
    <Scene key="a" />
    <Scene key="b" />
    <Scene key="c" />
</Router>

How could I setting backAndroidHandler in different scene or in the Tag to achieve this without setState (Because it will rerender again at route page)?

I have tried someone said in other question using like <Scene key="c" type={ActionConst.RESET}/> didn't work.

Any help or recommend will be appreciate. Thanks.

After researching some times, I found another way to achieve this effect.

Use BackHandler from react-native to add a listener to listen physical back button trigger, and then compare with react-native-router-flux Actions.currentScene to defined what should they do in different page like this:

import { Text, StyleSheet, Image, View, BackHandler, TouchableOpacity } from "react-native";
...

class ResultsView extends Component {
  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick); //here
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
  }
  handleBackButtonClick() {
    let cs = Actions.currentScene;
    if (cs === "APage" || cs === "BPage" || cs === "CPage" || cs === "DPage") {
      console.log("nono square don't pop!")
    } else {
      Actions.pop()
      console.log("touch to pop here")
    }
  }
...

And then set the backAndroidHandler in router to true:

<CustomRouter backAndroidHandler={true}>
...

And it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM