React Native (一)——界面间传值,DeviceEventEmitter 和 Navigator

DeviceEventEmitter

A界面push到B界面,B界面再pop回A界面,可以给A界面传值或者刷新A界面

A界面有个按钮点击进入B界面,在B界面中做了某些操作,然后点击回退按钮回到A页面,A页面中的数据也需要刷新过来

(生命周期: react native 中的生命周期是指组件的生命周期,不是指页面的生命周期。)

A界面注册,接收消息

import {devicEventEmitter} from 'react-native';

//注册这个监听事件
componentDidMount() {
   this.listener = DeviceEventEmitter.addListener('通知名称',(e)=>{ alert(e)});
}

//组件销毁时移除监听
componentWillUnmout() {
   this.listener.remove( );
}

B调用(实现刷新),发送消息

import  {
2 DeviceEventEmitter
3 } from 'react-native';
4 
5 //调用事件通知  param是指传递的相应参数
6 DeviceEventEmitter.emit('通知名称’,param);

Navigator管理

正向:传递Props

A界面传值

onClicAtoB( ){
    this.props.navigator.push({
            title:"pageB",
            component:ComponentName, 
            passProps:{
            breceive1:"data-tran to B",
            breceive2:[object]
            }
       }
    );
}

B界面取值

this.props.breceive1,
this.props.breceive2

逆向:传递function

A界面取值

扫描二维码关注公众号,回复: 3312916 查看本文章
onClickAJumpToB(){
    this.props.navigator.push({
                    title: 'PageB',
                    component: ComponentName,
                    passProps: {
                       // 注意:写法1。传递func,回调 - 要绑定 this,否则找不到()
                        xxCallback: function (arg, ...) {
                            // 更改state,触发refresh, 其中arg即为回传的值
                            this.setState({
                                key: arg,
                                ...
                            });
                        }.bind(this),

                        // 注意:写法2。绑定this, 
                        // 其中newFuncForCallback为A中,另一function,如下下下...
                        xxCallback: this.newFuncForCallback.bind(this),

                        // 注意:写法3。ES6,箭头函数,无需bind
                        xxCallback: (arg, ...) =>  {
                            // 更改state,触发refresh, 其中arg即为回传的值
                            this.setState({
                                key: arg,
                                ...
                            });
                        },
                       ...
                    }
                }
            );
}

// 回调函数,写法2中的function
newFuncForCallback(){
    // do somthing ...
}

Page B  传值

onClickBPopToA(){
    if(this.props.xxCallback){
        // 可传多个内容
        this.props.xxCallback(arg, ...);
    }
}

猜你喜欢

转载自blog.csdn.net/Rqlinna/article/details/82285462