反应本机全局后处理

时间:2018-08-02 10:36:07

标签: reactjs react-native

我有3个组成部分:

  1. ComponentA
  2. ComponentB
  3. BackPressHandlingComponent

BackPressHandlingComponent处理后推。

从ComponentA向后按下时;我必须退出该应用程序。

从ComponentB向后按下时;我必须去ComponentA。

这是我的BackPressHandlingComponent代码-

import { BackHandler } from 'react-native';

export class BackPressHandlingComponent extends Component {
    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
    }
} 

我的问题是-

如何从组件A告诉BackPressHandlingComponent我必须退出应用程序,并从组件B告诉我需要返回组件A

2 个答案:

答案 0 :(得分:0)

根据您的用例,我会在ComponentA和ComponentB上添加Backpress event listeners,这样当您在ComponentA上时,调用回调时就可以退出应用程序,而在ComponentB中调用其回调时,可以导航到ComponentA。

上述解决方案的简单演示:

App.js

/**
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native';
import ComponentA from './ComponentA'
import ComponentB from './ComponentB'
import BackHandlerHOC from './BackHandlerHOC'

type Props = {};
export default class App extends Component<Props> {
  state = {
    render: 'A'
  }

  toggleComponent = () => {
    let component = 'A'
    if (this.state.render === 'A') {
      component = 'B'
    }
    this.setState({ render: component })
  }

  render() {
    const { render } = this.state
    const wrappercomponent = render === 'A' ? (
      <BackHandlerHOC
        name="ComponentA"
        Component={ComponentA}
      />
    ) : (
        <BackHandlerHOC
          name="ComponentB"
          Component={ComponentB}
        />
      )
    return (
      <View style={styles.container}>
        <TouchableOpacity
          onPress={() => this.toggleComponent()}
        >
          <Text> Change </Text>
        </TouchableOpacity>
        {wrappercomponent}
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    padding: 20
  }
})

ComponentA

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class ComponentA extends Component {
  render() {
    return (
      <View>
        <Text>A</Text>
      </View>
    );
  }
}

export default ComponentA;

ComponentB

import React, { Component } from 'react';
import { View, Text } from 'react-native';

class ComponentB extends Component {
  render() {
    return (
      <View>
        <Text>B</Text>
      </View>
    );
  }
}

export default ComponentB;

BackHandlerHOC

import React, { Component } from 'react';
import { BackHandler, ToastAndroid, View, Text } from 'react-native';

class BackHandlerHOC extends Component {
  componentDidMount = () => {
    BackHandler.addEventListener('hardwareBackPress', this.backPressHandler);
  };

  componentWillUnmount = () => {
    BackHandler.removeEventListener('hardwareBackPress', this.backPressHandler);
  };

  backPressHandler = () => {
    const { name } = this.props;
    if (name === 'ComponentA') {
      BackHandler.exitApp()
    } else {
      // this.props.navigator.resetTo({
      //   screen: 'ComponentA'
      // })
      ToastAndroid.show('will go back to A', 0);
    }
    return true;
  };

  render() {
    const { Component } = this.props;
  return (
    <View>
      <Text>Hello from backpress</Text>
      <Component />
    </View>
);
  }
}

export default BackHandlerHOC;

您还可以在here世博会上找到工作示例

希望这会有所帮助

答案 1 :(得分:0)

只需添加另一种方法, 我利用了react-navigation生命周期事件和hardwareBackPress事件,请注意,这里react-navigation的版本是3.x.x

当屏幕进入视图时,将调用生命周期事件onWillFocus,而当用户移至另一个屏幕时,将调用生命周期事件onWillBlur,在某种程度上,React生命周期事件位于react-navigation之手,因此无法在这里使用它们,请参阅https://reactnavigation.org/docs/3.x/navigation-lifecycle.

以下是代码:

import { BackHandler,Alert } from "react-native";
import { NavigationEvents } from 'react-navigation';
class SomeComponent {
             //...my componentDidMount etc and other methods..... 

   backButtonAction(){
            Alert.alert(
            "Confirm Exit",
            "Do you want to exit the app?",
            [
              {
                text: "No",
                onPress: () => {},
                style: "cancel"
              },
              { text: "Yes", onPress: () => BackHandler.exitApp() }
            ],
            { cancelable: false }
          );
          return true; // coz the event handler needs to return boolean.
        };  
  setBackButtonAction(){
        BackHandler.addEventListener(
                        "hardwareBackPress",
                        this.backButtonAction
                      );
  }
  removeBackButtonAction(){
        BackHandler.removeEventListener(
                      "hardwareBackPress",
                      this.backButtonAction
                    );
  }
  render() {
                    return (
                          <Container>
                            <NavigationEvents
                            onWillFocus={payload => this.setBackButtonAction()}
                            onWillBlur={payload => this.removeBackButtonAction()}
                            /> //..... my view code
                          </Container>)
          }
    }