React Native移動開發實戰-3-實現頁面間的資料傳遞

來源:互聯網
上載者:User

標籤: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擷取navigatorif (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-實現頁面間的資料傳遞

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.