iT邦幫忙

2024 iThome 鐵人賽

DAY 25
0
佛心分享-SideProject30

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

[Day 25] 功能開發-餐點類別做成元件管理

  • 分享至 

  • xImage
  •  

今天要分享的是,由於考慮到使用者以及管理者版本都需要用到類別的UI元件,只是再傳入字串的不同,所以可以考慮封裝成程式元件管理,以下步驟

  • components 資料夾建立一支 Category.js 檔案
  • 設定按鈕事件 onPress
  • 撰寫 handleButtonPress 函式事件
  • useState 設定按鈕顯示的狀態
  • 匯出元件

完整程式碼

import React, {useState} from 'react';
import {TouchableOpacity, View, Text} from 'react-native';

const Category = () => {
  const [selectedButton, setSelectedButton] = useState('daily'); // 初始选中每日精选按钮

  const handleButtonPress = buttonType => {
    setSelectedButton(buttonType);
  };

  return (
    <View style={{flex: 0.5, flexDirection: 'row'}}>
      <View style={{flex: 0.1}}></View>

      <TouchableOpacity
        style={{
          flex: 0.35,
          borderRadius: 5,
          backgroundColor: selectedButton === 'daily' ? 'orange' : 'white',
          borderWidth: 1,
          borderColor: selectedButton === 'all' ? 'orange' : '#fff',
          justifyContent: 'center',
          alignItems: 'center',
        }}
        onPress={() => handleButtonPress('daily')}>
        <Text
          style={{
            color: selectedButton === 'all' ? 'orange' : '#fff',
            textAlign: 'center',
          }}>
          每日精選
        </Text>
      </TouchableOpacity>

      <View style={{flex: 0.05}}></View>

      <TouchableOpacity
        style={{
          flex: 0.35,
          borderRadius: 5,
          backgroundColor: selectedButton === 'all' ? 'orange' : 'white',
          borderColor: selectedButton === 'all' ? 'white' : 'orange',
          borderWidth: 1,
          justifyContent: 'center',
          alignItems: 'center',
        }}
        onPress={() => handleButtonPress('all')}>
        <Text
          style={{
            color: selectedButton === 'all' ? 'white' : 'orange',
            textAlign: 'center',
          }}>
          全部菜單
        </Text>
      </TouchableOpacity>

      <View style={{flex: 0.1}}></View>
    </View>
  );
};

export default Category;


上一篇
[Day 24] 功能開發-購物車頁面
系列文
用React Native打造找餐店APP25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言