《React Native移动开发实战》一一3.8实现页面间的数据传递

    xiaoxiao2021-07-23  265

    3.8 实现页面间的数据传递跳转和返回的效果实现了,那么,如何实现页面间的数据传递和通信呢?其实,从上述代码中读者已经可以发现:React Native使用props来实现页面间数据传递和通信。在React Native中,有两种方式可以存储和传递数据,即props(属性)以及state(状态),其中:? props通常是在父组件中指定的,而且一经指定,在被指定的组件的生命周期中则不再改变。? state通常是用于存储需要改变的数据,并且当state数据发生更新时,React Native会刷新界面。了解了props与state的区别之后,读者应该知道,要将首页的数据传递到下一个页面,需要使用props。所以修改home.js代码如下:

    01 export default class home extends React.Component { 02 // 这里省略了没有修改的代码 03 04 _renderRow = (rowData, sectionID, rowID) => { 05 return ( 06 <TouchableHighlight onPress={() => { 07 const {navigator} = this.props; // 从props获取navigator 08 if (navigator) { 09 navigator.push({ 10 name: 'detail', 11 component: Detail, 12 params: { 13 productTitle: rowData.title // 通过params传递props 14 } 15 }); 16 } 17 }}> 18 // 这里省略了没有修改的代码 19 </TouchableHighlight> 20 ); 21 } 22 }

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

    01 export default class detail extends React.Component { 02 render() { 03 return ( 04 <View style={styles.container}> 05 <TouchableOpacity onPress={this._pressBackButton.bind (this)}> 06 <Text style={styles.back}>返回</Text> 07 </TouchableOpacity> 08 <Text style={styles.text}> 09 {this.props.productTitle} 10 </Text> 11 </View> 12 ); 13 } 14 15 // 这里省略了没有修改的代码 16 }

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

    图3.31 详情页面显示单击的商品名称这样,一个完整的页面跳转和页面间数据传递的功能就实现了。


    最新回复(0)