iT邦幫忙

2024 iThome 鐵人賽

DAY 19
0
佛心分享-SideProject30

用React Native打造找餐店APP系列 第 19

[Day 19] 功能開發-學習建立組件

  • 分享至 

  • xImage
  •  

昨天,我們已經建立好 navigation 容器,接下來會新增頁面,並製作頁面表頭組件。以下是具體步驟:

1.建立 Order.js

//import liraries
import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';

// create a component
const OrderPage = () => {
  return (
    <View style={styles.container}>
      <Text>MyComponent</Text>
    </View>
  );
};

// define your styles
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
});

//make this component available to the app
export default OrderPage;

2.製作頁面表頭組件
在應用程式中,我們經常會在不同頁面間使用相同的表頭組件。為了重用性,我們可以將其拆解成一個共用元件。

src 目錄下建立 components 資料夾,並在此新增 Header.js 檔案,編寫以下程式碼:

寫法一

import React from 'react';
import {View, Text} from 'react-native';
 
const _header = props => {
  return (
    <View
      style={{
        flexDirection: 'row',
        backgroundColor: 'orange',
        justifyContent: 'center',
        padding: 10,
        alignItems: 'center',
      }}>
      <Text style={{color: '#fff', fontWeight: 'bold', fontSize: 18}}>
        {props.hederText}
      </Text>
    </View>
  );
};

export default _header;

寫法二

為避免定義好的 function 元件未被匯出導致無法渲染,可以使用 export default 進行匯出:
如果有多個元件需要匯出,則使用具名匯出:

export const HeaderBar = () => {
  return(
     ... 
  )
}
export const HeaderSection = () => {
  return(
     ... 
  )
}

在匯入時,可以使用解構方式來匯入指定的元件:

import {HeaderBar,HeaderSection} from './components/Header.js'
export default header(props) {
  return (
    <View
      style={{
        flexDirection: 'row',
        backgroundColor: 'orange',
        justifyContent: 'center',
        padding: 10,
        alignItems: 'center',
      }}>
      <Text style={{color: '#fff', fontWeight: 'bold', fontSize: 18}}>
        {props.hederText}
      </Text>
    </View>
  );
};

製作好表頭組件後,在 Order.js 中將其匯入:

import _Header from '../components/_header';

然後在頁面中決定好位置並渲染出來:

      <View style={{flex: 0.1}}>
        <_Header hederText="挑選早餐" />
      </View>

這樣,我們就成功地將表頭組件放到了 Order.js 頁面中。


上一篇
[Day 18] 功能開發-來切第一個頁面吧
下一篇
[Day 20] 功能開發-列表顯示元件
系列文
用React Native打造找餐店APP25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言