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

前端之家收集整理的这篇文章主要介绍了React Native移动开发实战-3-实现页面间的数据传递前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

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

  1. export default class home extends React.Component {
  2. // 这里省略了没有修改代码
  3.  
  4. _renderRow = (rowData,sectionID,rowID) => {
  5. return (
  6. <TouchableHighlight onPress={() => {
  7. const {navigator} = this.props; // 从props获取navigator
  8. if (navigator) {
  9. navigator.push({
  10. name: 'detail',component: Detail,params: {
  11. productTitle: rowData.title // 通过params传递props
  12. }
  13. });
  14. }
  15. }}>
  16. // 这里省略了没有修改代码
  17. </TouchableHighlight>
  18. );
  19. }
  20. }

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

export default class detail extends React.Component {

  1. render() {
  2. return (
  3. <View style={styles.container}>
  4. <TouchableOpacity onPress={this._pressBackButton.bind(this)}>
  5. <Text style={styles.back}>返回</Text>
  6. </TouchableOpacity>
  7. <Text style={styles.text}>
  8. {this.props.productTitle}
  9. </Text>
  10. </View>
  11. );
  12. }
  13.  
  14. // 这里省略了没有修改代码

}

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

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

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

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

猜你在找的React相关文章