今天來分享在業主版的APP中,查看訂單狀態的類別切換元件,將其封裝成元件管理,並改善寫法:
import React, {useState} from 'react';
import {TouchableOpacity, View, Text} from 'react-native';
const OrderStatusBar = () => {
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 OrderStatusBar;
將以上程式碼改寫:
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, StyleSheet } from 'react-native';
const OrderStatusBar = ({ buttonLabels, onButtonPress }) => {
const [selectedButton, setSelectedButton] = useState(buttonLabels[0]);
const handleButtonPress = buttonType => {
setSelectedButton(buttonType);
onButtonPress(buttonType); // 通過 props 回調外部方法
};
return (
<View style={styles.container}>
{buttonLabels.map((label, index) => (
<React.Fragment key={label}>
<TouchableOpacity
style={[
styles.button,
{
backgroundColor: selectedButton === label ? 'orange' : 'white',
borderColor: selectedButton === label ? 'white' : 'orange',
},
]}
onPress={() => handleButtonPress(label)}
>
<Text
style={{
color: selectedButton === label ? 'white' : 'orange',
}}
>
{label}
</Text>
</TouchableOpacity>
{index < buttonLabels.length - 1 && <View style={styles.spacer} />}
</React.Fragment>
))}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 0.5,
flexDirection: 'row',
alignItems: 'center',
},
button: {
flex: 0.35,
borderRadius: 5,
borderWidth: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
},
spacer: {
flex: 0.05,
},
});
export default OrderStatusBar;