React Native学习之物理back键详解

基本使用

在前文代码的基础上,分析路由栈的结构:Home -> Gouwu

栈:先进后出,后进先出

点击返回键返回上一级页面关键代码:

componentWillMount() {
    if (Platform.OS === 'android') {
        BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
}

componentWillUnmount() {
    if (Platform.OS === 'android') {
        BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
}

onBackAndroid = () => {
    const { navigator } = this.props;
    const routers = navigator.getCurrentRoutes();
    console.log('当前路由长度:'+routers.length);
    if (routers.length > 1) {
        navigator.pop();
        return true;  //接管默认行为
    }
    return false;  //默认行为
};

需要注意的是,不论是bind方式还是箭头函数,每次被执行都返回的是一个新的函数引用,因此如果还需要使用函数的引用去做一些别的事情(譬如卸载监听器),那么必须手动保存这个引用。

// 错误的做法
class PauseMenu extends React.Component {
    componentWillMount() {
        AppStateIOS.addEventListener('change', this.onAppPaused.bind(this));
    }
    componentDidUnmount() {
        AppStateIOS.removeEventListener('change', this.onAppPaused.bind(this));
    }
    onAppPaused(event) {
    }
}
// 正确的做法1
class PauseMenu extends React.Component {
    constructor(props) {
        super(props);
        this._onAppPaused = this.onAppPaused.bind(this);
    }
    componentWillMount() {
        AppStateIOS.addEventListener('change', this._onAppPaused);
    }
    componentDidUnmount() {
        AppStateIOS.removeEventListener('change', this._onAppPaused);
    }
    onAppPaused(event) {
    }
}
// 正确的做法2
class PauseMenu extends React.Component{
    componentWillMount() {
        AppStateIOS.addEventListener('change', this.onAppPaused);
    }
    componentDidUnmount() {
        AppStateIOS.removeEventListener('change', this.onAppPaused);
    }
    onAppPaused = (event) => {
        //把方法直接作为一个arrow function的属性来定义,初始化的时候就绑定好了this指针
    }
}

特别说明

  • BackAndroid在iOS平台下是一个空实现,所以理论上不做这个Platform.OS === 'android'判断也是安全的。
  • 如果所有事件监听函数中,没有任何一个返回真值,就会调用默认行为。

特别注意

无论在Home页面中调用,还是在Gouwu页面中调用“点击返回键返回上一级页面代码”,navigator是同一个,这个事件在最外层注册就行(不是initialRoute的组件,是AppRegistry的组件)。否则如果在Home页面和Gouwu页面分别调用,会导致调用多次pop,这个代码接管的是整个应用的后退键。

addEventListener()第三个参数useCapture (Boolean)详细解析:

  • true 的触发顺序总是在 false 之前;
  • 如果多个均为 true,则外层的触发先于内层;
  • 如果多个均为 false,则内层的触发先于外层。

例子:“再按一次退出应用”

onBackAndroid = () => {
    const navigator = this.refs.navigator;
    const routers = navigator.getCurrentRoutes();
    console.log('当前路由长度:' + routers.length);
    if (routers.length > 1) {
        navigator.pop();
        return true; //接管默认行为
    } else {
        if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
            //最近2秒内按过back键,可以退出应用。
            return false;
        }
        this.lastBackPressed = Date.now();
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
        return true;
    }
    return false; //默认行为
};

特殊监听事件

延时动作

我们在监听函数中不能决定是否要调用默认行为,要等待一个异步操作之后才调用默认行为,此时可以使用BackAndroid.exitApp()来退出应用,通过以下两种办法:

例子:在退出应用之前保存数据

写法1:

onBackAndroid = () => {
    saveData().then(() => {
        BackAndroid.exitApp();
    });
    return true;
}

在监听函数中,我们开始异步事件,并直接return true。此时默认行为不会被调用。当保存完毕后,我们调用exitApp(),触发默认行为,退出应用。

写法2:

onBackAndroid = async () => {
    await saveData();
    BackAndroid.exitApp();
}

这里我们用了async函数,async 函数总是返回一个Promise,Promise作为一个对象,也被认为是一个“真值”,所以这种情况下默认行为总是不会被调用。当保存完毕后,我们调用exitApp(),触发默认行为,退出应用。

多样动作

例子:根据当前界面决定作何动作

有时候我们有这样的需求:当用户处于某些界面下时,back键要做特殊的动作,如:提示用户是否要保存数据,或者解锁界面禁止back键返回等等。此时,最佳实践是在route或route中对应的Component上保存关于如何处理back键的信息:

onBackAndroid = () => {
    const nav = this.navigator;
    const routers = nav.getCurrentRoutes();
    if (routers.length > 1) {
        const top = routers[routers.length - 1];
        if (top.ignoreBack || top.component.ignoreBack) {
            // 路由或组件上决定这个界面忽略back键
            return true;
        }
        const handleBack = top.handleBack || top.component.handleBack;
        if (handleBack) {
            // 路由或组件上决定这个界面自行处理back键
            return handleBack();
        }
        // 默认行为:退出当前界面。
        nav.pop();
        return true;
    }
    return false;
};

全部代码:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    Navigator,
    ScrollView,
    Image,
    AsyncStorage,
    TouchableOpacity,
    View,
    Platform,
    BackAndroid,
    ToastAndroid,
} from 'react-native';

import Dimensions from 'Dimensions';

const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;

const Model = [
    {
        id: '1',
        title: '红心猕猴桃',
        desc: '12个装70-90g/个',
        price: 49,
        url: 'http://note.youdao.com/yws/api/personal/file/62EAF0C6AC8142EA89B11A71BB6C8AEC?method=download&inline=true&shareKey=e6b1c5b1307f752c9e4925056a4facd9',
    },
    {
        id: '2',
        title: '红富士苹果',
        desc: '5kg果径80-85mm',
        price: 109,
        url: 'http://note.youdao.com/yws/api/personal/file/E38B11859CB2496190BF5A559D9E68B5?method=download&inline=true&shareKey=1dabf3633a1051e9f5d2d7470fd91c0b',
    },
    {
        id: '3',
        title: '哈密瓜',
        desc: '2个装1.4kg以上/个',
        price: 42,
        url: 'http://note.youdao.com/yws/api/personal/file/F443648C199346FDA7E48AE88D0D00A2?method=download&inline=true&shareKey=89fdcc577f98ecdddfcf03f575767381',
    },
    {
        id: '4',
        title: '青芒',
        desc: '1kg500g以上/个',
        price: 28,
        url: 'http://note.youdao.com/yws/api/personal/file/8F7B83A47CA94435A2132DC0341AECC3?method=download&inline=true&shareKey=d679e8800b5678f9c673538b93dc0fbc',
    },
    {
        id: '5',
        title: '黑珍珠葡萄',
        desc: '1kg装',
        price: 32,
        url: 'http://note.youdao.com/yws/api/personal/file/AF297F8C75714DE481E87C6F09D97649?method=download&inline=true&shareKey=8f89c3673e8851efb20abccce2214fbf',
    },
    {
        id: '6',
        title: '红心火龙果',
        desc: '2.5kg装250-350g/个',
        price: 59.9,
        url: 'http://note.youdao.com/yws/api/personal/file/B67D0D453865459594C0FDC6CDE95A79?method=download&inline=true&shareKey=3bc5b3b1ee9f13e3a7ebdd251d117796',
    },
];

class RNAPP extends Component {
    render() {
        let defaultName = 'Home';
        let defaultComponent = Home;
        return (
            <Navigator
                initialRoute = {{ name: defaultName, component: defaultComponent }}
                ref = "navigator"
                //配置场景
                configureScene = {
                    (route) => {
                        //这个是页面之间跳转时候的动画,具体有哪些?可以看这个目录下,有源代码的: node_modules/react-native/Libraries/CustomComponents/Navigator/NavigatorSceneConfigs.js
                        return Navigator.SceneConfigs.VerticalDownSwipeJump;
                    }
                }
                renderScene = {
                    (route, navigator) => {
                        let Component = route.component;
                        return <Component {...route.params} navigator={navigator} />
                    }
                }
            />
        );
    }

    componentWillMount() {
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
            //BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid, true);
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    }

    onBackAndroid = () => {
        const navigator = this.refs.navigator;
        const routers = navigator.getCurrentRoutes();
        console.log('当前路由长度:' + routers.length);
        if (routers.length > 1) {
            navigator.pop();
            return true; //接管默认行为
        } else {
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                //最近2秒内按过back键,可以退出应用。
                return false;
            }
            this.lastBackPressed = Date.now();
            ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
            return true;
        }
        return false; //默认行为
    };
}

class Home extends Component {
    render() {
        return (
            <List navigator={this.props.navigator} />
        );
    }
}

class Item extends Component {
    static defaultProps = {
        url: '',
        title: '默认标题',
    };

    static propTypes = {
        url: React.PropTypes.string.isRequired,
        title: React.PropTypes.string.isRequired,
    };

    render() {
        return (
            <View style={styles.item}>
                <TouchableOpacity onPress={this.props.press}>
                    <Image
                        resizeMode='stretch'
                        style={styles.img}
                        source={{ uri: this.props.url }}
                        >
                        <Text numberOfLines={1} style={styles.item_text}>{this.props.title}</Text>
                    </Image>
                </TouchableOpacity>
            </View>
        );
    }
}

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        };
    }

    render() {
        let list = [];
        for (let i in Model) {
            if (i % 2 === 0) {
                //两个等号:不判断类型
                //三个等号:判断类型
                let row = (
                    <View style={styles.row} key={i}>
                        <Item
                            title={Model[i].title}
                            url={Model[i].url}
                            press={this.press.bind(this, Model[i]) }
                            >
                        </Item>
                        <Item
                            title={Model[parseInt(i) + 1].title}
                            url={Model[parseInt(i) + 1].url}
                            press={this.press.bind(this, Model[parseInt(i) + 1]) }
                            >
                        </Item>
                    </View>
                );
                list.push(row);
            }
        }

        let count = this.state.count;
        let str = null;
        if (count) {
            str = ', 共' + count + '件商品';
        }
        console.log('count=' + count);

        return (
            <ScrollView style={{ marginTop: 10 }}>
                {list}
                <Text onPress={this.goGouWu.bind(this) } style={styles.btn}>去结算{str}</Text>
            </ScrollView>
        );
    }

    goGouWu() {
        //alert('点击了去购物车');
        const { navigator } = this.props;
        //为什么这里可以取得 props.navigator?请看上文:
        //<Component {...route.params} navigator={navigator} />
        //这里传递了navigator作为props
        const _that = this;
        if (navigator) {
            navigator.push({
                name: 'GouWu',
                component: GouWu,
                params:{
                    getCount: function(count) {
                        _that.setState({
                            count: count,
                        });
                        console.log('参数传回');
                    },
                },
            })
        }
    }

    press(data) {
        this.setState({
            count: this.state.count + 1,
        });
        //AsyncStorage异步存储
        AsyncStorage.setItem('SP-' + this.genId() + '-SP', JSON.stringify(data), function (err) {
            if (err) {
                //TODO:存储出错
                alert(err);
            } else {
                //alert('保存成功');
            }
        });
    }

    //生成随机ID:GUID 全局唯一标识符(GUID,Globally Unique Identifier)是一种由算法生成的二进制长度为128位的数字标识符
    //GUID生成的代码来自于Stoyan Stefanov
    genId() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    componentDidMount() {
        let _that = this;
        AsyncStorage.getAllKeys(
            function (err, keys) {
                if (err) {
                    //TODO:存储取数据出错
                    //给用户提示错误信息
                    console.log(err);
                } else {
                    console.log('读取成功的个数:'+keys.toString());
                }
                _that.setState({
                    count: keys.length,
                });
            }
        );
    }
}

class GouWu extends Component {
    constructor(props) {
        super(props);
        this.state = {
            price: 0,
            data: [],
        };
    }

    render() {
        //第二次render的时候 data不为空
        let data = this.state.data;
        let price = this.state.price;
        let list = [];
        for (let i in data) {
            price += parseFloat(data[i].price);
            list.push(
                <View style={[styles.row, styles.list_item]} key={i}>
                    <Text style={styles.list_item_desc}>
                        {data[i].title}
                        {data[i].desc}
                    </Text>
                    <Text style={styles.list_item_price}>人民币: {data[i].price}</Text>
                </View>
            );
        }

        let str = null;
        if (price) {
            str = ', 共' + price.toFixed(2) + '元';
        }

        return (
            <ScrollView style={{ marginTop: 10 }}>
                {list}
                <Text style={styles.btn} onPress={this.paySuccess.bind(this)} >支付{str}</Text>
                <Text style={styles.clear} onPress={this.clearStorage.bind(this) }>清空购物车</Text>
            </ScrollView>
        );
    }

    componentDidMount() {
        let _that = this;
        AsyncStorage.getAllKeys(
            function (err, keys) {
                if (err) {
                    //TODO 存储数据出错
                    return;
                }
                //keys是字符串数组
                AsyncStorage.multiGet(keys, function (err, result) {
                    //得到的结构是二维数组
                    //result[i][0]表示我们存储的键,result[i][1]表示我们存储的值
                    let arr = [];
                    for (let i in result) {
                        arr.push(JSON.parse(result[i][1]));
                    }

                    _that.setState({
                        data: arr,
                    });
                });
            }
        );
    }

    paySuccess() {
        var _that = this;
        AsyncStorage.clear(function(err){
            if (!err) {
                _that.setState({
                    data: [],
                    price: 0,
                });

                const { navigator } = _that.props;
                if (_that.props.getCount) {
                    _that.props.getCount(0);
                }

                alert("支付成功!")

                if (navigator) {
                    navigator.pop();
                }
                //_that.props.navigator.pop();
            }
        });
    }

    clearStorage() {
        let _that = this;
        AsyncStorage.clear(function (err) {
            if (!err) {
                _that.setState({
                    data: [],
                    price: 0,
                });
                alert('购物车已经清空');
            }
        });
    }
}

const styles = StyleSheet.create({
    list_item: {
        marginLeft: 5,
        marginRight: 5,
        padding: 5,
        borderWidth: 1,
        height: 32,
        borderRadius: 3,
        borderColor: '#ddd',
    },
    list_item_desc: {
        flex: 2,
        fontSize: 15,
    },
    list_item_price: {
        flex: 1,
        fontSize: 15,
        textAlign: 'right',
    },
    clear: {
        marginTop: 10,
        backgroundColor: '#FF7200',
        color: '#fff',
        borderWidth: 1,
        borderColor: '#ddd',
        marginLeft: 10,
        marginRight: 10,
        lineHeight: 24,
        height: 33,
        fontSize: 18,
        textAlign: 'center',
        textAlignVertical: 'center',
    },
    btn: {
        flex: 1,
        backgroundColor: '#FF7200',
        height: 33,
        textAlign: 'center',
        textAlignVertical: 'center',
        color: '#fff',
        marginLeft: 10,
        marginRight: 10,
        lineHeight: 24,
        marginTop: 40,
        fontSize: 18,
    },
    row: {
        flexDirection: 'row',
        marginBottom: 10,
    },
    img: {
        flex: 1,
        backgroundColor: 'transparent',
    },
    item_text: {
        backgroundColor: '#000',
        opacity: 0.7,
        color: '#fff',
        height: 25,
        lineHeight: 18,
        textAlign: 'center',
        marginTop: 94,
    },
    item: {
        flex: 1,
        marginLeft: 5,
        borderWidth: 1,
        borderColor: '#ddd',
        marginRight: 5,
        height: 120,
    },
    list: {
        justifyContent: 'flex-start',
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    container: {

        flex: 1,
    },
    listView: {
        paddingTop: 20,
        backgroundColor: '#F5FCFF',
    },
    thumbnail: {
        width: 80,
        height: 80,
        borderRadius: 16,
    },
    //使rightContainer在父容器中占据Image之外剩下的全部空间
    container1: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    title: {
        fontSize: 14,
        marginBottom: 8,
    },
    year: {
        fontSize: 14,
    },
});

AppRegistry.registerComponent('RNAPP', () => RNAPP);

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/02/25/react-native-learning-for-detailed-explanation-of-the-physical-back-key/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
React Native学习之物理back键详解
基本使用 在前文代码的基础上,分析路由栈的结构:Home -> Gouwu 栈:先进后出,后进先出 点击返回键返回上一级页面关键代码: componentWillMount() { ……
<<上一篇
下一篇>>
文章目录
关闭
目 录