React Native【实战范例】 Tab 切换

发布于:2025-06-28 ⋅ 阅读:(19) ⋅ 点赞:(0)

最终效果

在这里插入图片描述

技术要点

  • 要响应点击事件,需用 TouchableOpacity

  • 最左边和最右边的边框圆角实现

    index === 0 && styles.leftItem,
    index === TypeList.length - 1 && styles.rightItem,
    
          leftItem: {
            borderTopLeftRadius: 8,
            borderBottomLeftRadius: 8,
          },
          rightItem: {
            borderTopRightRadius: 8,
            borderBottomRightRadius: 8,
          },
    
  • 添加 1 的左外边距,避免边框重合

    index > 0 && styles.moveLeft1Pix,
    
    moveLeft1Pix: {
            marginLeft: -1,
    },
    
  • 高亮样式在容器和文本上都要添加

     <Text style={[type === item && styles.activeItem]}>{item}</Text>
    

    TouchableOpacity 上也有

    type === item && styles.activeItem,
    
  • 使用 useCallback 提升性能

代码范例

import { useCallback, useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
const [type, setType] = useState("微信");
  const Render_Type = () => {
    const TypeList = ["微信", "QQ", "支付宝"];
    const handlePress = useCallback((item: string) => {
      setType(item);
    }, []);
    const styles = StyleSheet.create({
      typeBox: {
        display: "flex",
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        marginTop: 10,
      },
      itemBox: {
        borderWidth: 1,
        borderColor: "#C0C0C0",
        flex: 1,
        height: 30,
        justifyContent: "center",
        alignItems: "center",
      },
      moveLeft1Pix: {
        marginLeft: -1,
      },
      leftItem: {
        borderTopLeftRadius: 8,
        borderBottomLeftRadius: 8,
      },
      rightItem: {
        borderTopRightRadius: 8,
        borderBottomRightRadius: 8,
      },
      activeItem: {
        backgroundColor: "#007AFF",
        color: "#fff",
      },
    });
    return (
      <View style={styles.typeBox}>
        {TypeList.map((item, index) => (
          <TouchableOpacity
            activeOpacity={0.5}
            onPress={() => handlePress(item)}
            key={item}
            style={[
              styles.itemBox,
              index > 0 && styles.moveLeft1Pix,
              index === 0 && styles.leftItem,
              index === TypeList.length - 1 && styles.rightItem,
              type === item && styles.activeItem,
            ]}
          >
            <Text style={[type === item && styles.activeItem]}>{item}</Text>
          </TouchableOpacity>
        ))}
      </View>
    );
  };

网站公告

今日签到

点亮在社区的每一天
去签到