码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-08-17 21:25:04      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:data   sdn   net   bsp   leo   navig   font   section   改变   

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移动开发实战-3-实现页面间的数据传递

标签:data   sdn   net   bsp   leo   navig   font   section   改变   

原文地址:http://www.cnblogs.com/mochou/p/7384123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!