React Native BackHandler不删除事件侦听器

时间:2017-09-24 16:14:27

标签: android react-native react-navigation

我正在使用React Navigation,按下后退按钮时我需要一些自定义功能。这是我的代码:

class AddEditIngredient extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editStarted: false
    };
    this.goBack = () => {
      if (this.state.editStarted === true) {
        Alert.alert(
          "Ingredient Not Saved",
          "Do you want to navigate away without saving ingredient?",
          [
            { text: "Cancel", onPress: () => null, style: "cancel" },
            { text: "Yes", onPress: () => this.props.navigation.goBack() }
          ],
          { cancelable: true }
        );
      } else {
        this.props.navigation.goBack();
      }
    };
}

componentWillMount() {
    BackHandler.addEventListener("hardwareBackPress", this.goBack);
}

componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.goBack);
}

我的goBack功能适用于屏幕上的后退按钮,但是当我尝试按下物理后退按钮时,它会弹出所有屏幕并最小化应用程序。通过阅读以前关于该问题的帖子我收集的内容,removeEventListener并不是指与addEventListener相同的函数。所以我尝试了这个:

constructor(props) {
    super(props);
    this.state = {
      editStarted: false
    };
    this.goBack = this.goBack.bind(this);
}
goBack = () => {
      if (this.state.editStarted === true) {
        Alert.alert(
          "Ingredient Not Saved",
          "Do you want to navigate away without saving ingredient?",
          [
            { text: "Cancel", onPress: () => null, style: "cancel" },
            { text: "Yes", onPress: () => this.props.navigation.goBack() }
          ],
          { cancelable: true }
        );
      } else {
        this.props.navigation.goBack();
      }
    };

但它没有用。谁能指出我的错误?

由于

2 个答案:

答案 0 :(得分:0)

最后在this post找到答案。我需要在goBack函数结束时返回true,以指示已经处理了后退行为。

答案 1 :(得分:0)

您需要在自定义后向监听器上附加return truereturn false才能跟随父处理程序