React Native - 屬性 (Props)



在上一章中,我們向您展示瞭如何使用可變的狀態 (state)。在本章中,我們將向您展示如何組合狀態和屬性 (props)

表現型元件應透過傳遞屬性 (props) 獲取所有資料。只有容器元件才應具有狀態 (state)

容器元件

現在我們將瞭解什麼是容器元件以及它的工作原理。

理論

現在我們將更新我們的容器元件。此元件將處理狀態並將屬性傳遞給表現型元件。

容器元件僅用於處理狀態。所有與檢視相關的功能(樣式等)都將在表現型元件中處理。

示例

如果我們想使用上一章中的示例,我們需要從 render 函式中刪除Text 元素,因為此元素用於向用戶呈現文字。這應該在表現型元件內。

讓我們回顧一下下面示例中的程式碼。我們將匯入PresentationalComponent 並將其傳遞給 render 函式。

匯入PresentationalComponent 並將其傳遞給 render 函式後,我們需要傳遞屬性。我們將透過新增myText = {this.state.myText}deleteText = {this.deleteText}<PresentationalComponent> 來傳遞屬性。現在,我們可以在表現型元件內訪問它。

App.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import PresentationalComponent from './PresentationalComponent'

export default class App extends React.Component {
   state = {
      myState: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, used do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
      nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
      aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
      nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
      officia deserunt mollit anim id est laborum.'
   }
   updateState = () => {
      this.setState({ myState: 'The state is updated' })
   }
   render() {
      return (
         <View>
            <PresentationalComponent myState = {this.state.myState} updateState = {this.updateState}/>
         </View>
      );
   }
}

表現型元件

現在我們將瞭解什麼是表現型元件以及它的工作原理。

理論

表現型元件僅用於向用戶呈現檢視。這些元件沒有狀態。它們接收所有資料和函式作為屬性。

最佳實踐是儘可能多地使用表現型元件。

示例

正如我們在上一章中提到的,我們正在為表現型元件使用 ES6 函式語法。

我們的元件將接收屬性、返回檢視元素、使用{props.myText}呈現文字,並在使用者單擊文字時呼叫{props.deleteText} 函式。

PresentationalComponent.js

import React, { Component } from 'react'
import { Text, View } from 'react-native'

const PresentationalComponent = (props) => {
   return (
      <View>
         <Text onPress = {props.updateState}>
            {props.myState}
         </Text>
      </View>
   )
}
export default PresentationalComponent

現在,我們具有與狀態 (State)章節中相同的功。唯一的區別是我們已將程式碼重構為容器元件和表現型元件。

您可以執行應用程式並檢視如下螢幕截圖中的文字。

React Native Props

如果您單擊文字,它將從螢幕中刪除。

React Native Props updated
廣告