加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React Native移动开发实战-3-实现页面间的数据传递

发布时间:2020-12-15 06:53:24 所属栏目:百科 来源:网络整理
导读:React Native使用props来实现页面间数据传递和通信。在React Native中,有两种方式可以存储和传递数据:props(属性)以及state(状态),其中: props通常是在父组件中指定的,而且一经指定,在被指定的组件的生命周期中则不再改变。 state通常是用于存储需

React Native使用props来实现页面间数据传递和通信。在React Native中,有两种方式可以存储和传递数据:props(属性)以及state(状态),其中:

  • props通常是在父组件中指定的,而且一经指定,在被指定的组件的生命周期中则不再改变。

  • state通常是用于存储需要改变的数据,并且当state数据发生更新时,React Native会刷新界面。

了解了props与state的区别之后,读者应该知道,要将首页的数据传递到下一个页面,需要使用props。所以,修改home.js代码如下:

export default class home extends React.Component {
    // 这里省略了没有修改的代码

    _renderRow = (rowData,sectionID,rowID) => {
        return (
            <TouchableHighlight onPress={() => {
                const {navigator} = this.props;             // 从props获取navigator
                if (navigator) {
                    navigator.push({
                        name: 'detail',component: Detail,params: {
                            productTitle: rowData.title // 通过params传递props
                        }
                    });
                }
            }}>
                // 这里省略了没有修改的代码
            </TouchableHighlight>
        );
    }
}

在home.js中,为Navigator的push方法添加的参数params,会当做props传递到下一个页面,因此,在detail.js中可以使用this.props.productTitle来获得首页传递的数据。修改detail.js代码如下:

export default class detail extends React.Component {

render() {
    return (
        <View style={styles.container}>
            <TouchableOpacity onPress={this._pressBackButton.bind(this)}>
                <Text style={styles.back}>返回</Text>
            </TouchableOpacity>
            <Text style={styles.text}> 
                {this.props.productTitle}
            </Text>
        </View>
    );
}

// 这里省略了没有修改的代码

}

重新加载应用,当再次单击商品列表时,详情页面将显示单击的商品名称,效果如图3.31所示。

图3.31 详情页面显示单击的商品名称

这样,一个完整的页面跳转和页面间数据传递的功能就实现了。
和我一起学吧,《React Native移动开发实战》

和我一起学吧,《React Native移动开发实战》

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读