React Native学习笔记之--组件之间数据的传递和跳转

React Native学习笔记之–组件之间数据的传递和跳转

  • 自定义属性的定义方式和传递

假定组件ComponentA中的自定义属性为

static props = {
        title: '',
        data: ''
    }

数据的传递(这样在ComponentA便能接收到传递的数据了)

<ComponentA title='标题' data="数据"></ComponentA>
  • 利用Navigator传递数据(向组件DetailView传递数据,然后在DetailView的props中获取message的数据)

this.props.navigator.push({
            component: DetailView,
            passProps: {'message' : '利用导航传递数据'}
        });
  • 组件通过回调函数传递数据(类似原生开发的代理模式)

现在有一个需求,组件B中在主页中,现在需要点击组件B中的按钮,通过Navigator跳转到下一个页面中,并且携带数据。现在组件B中是拿不到this.props.navigator的,下面就通过回调的方式来处理这种需求。

这里写图片描述
解决方案:

1.在组件B中定义一个属性clickButtonCallback
2.点击组件B的按钮,判断clickButtonCallback是否实现,若实现,则调用
3.在主页中实现clickButtonCallback具体逻辑,跳转页面并传递参数

代码如下:
组件B

export default class ComponentB extends Component {

    static props = {
        clickButtonCallback: null,
    }

    render() {
        return (
            <View style={styles.container}>
                <Text>组件B</Text>
                <TouchableOpacity activeOpacity={0.5}
                                  style={{backgroundColor: 'yellow'}}
                                  onPress={() => {this.clickButton()}}

                >
                    <Text>按钮:进入下一个页面</Text>
                </TouchableOpacity>
            </View>
        );
    }

    clickButton() {
        if (this.props.clickButtonCallback == null) return;

        this.props.clickButtonCallback('传递的数据');
    }
}

const styles = StyleSheet.create({
    container: {
        height: 160,
        justifyContent: 'center',
        backgroundColor: 'green',
        alignItems: 'center'
    },
});

主页中的代码:

export default class HomeView extends Component {
    render() {
        return (
            <View style={styles.container}>
                <View style={{backgroundColor: '#e8e8e8', height: 64, justifyContent: 'center', alignItems: 'center'}}>
                    <Text style={{marginTop: 20}}>主页</Text>
                </View>

                <ComponentB clickButtonCallback={(data) => {this.clickComponentBMiddleButton(data)}}></ComponentB>
            </View>
        );
    }

    clickComponentBMiddleButton(data) {

        this.props.navigator.push({
            component: DetailView,
            passProps: {'message' : data}
        });
    }
}

效果如下:
这里写图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值