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 {
}
重新加载应用,当再次单击商品列表时,详情页面将显示单击的商品名称,效果如图3.31所示。
图3.31 详情页面显示单击的商品名称
这样,一个完整的页面跳转和页面间数据传递的功能就实现了。
和我一起学吧,《React Native移动开发实战》
和我一起学吧,《React Native移动开发实战》