You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native 如何实现带文本的带动画效果的双选项切换按钮

React Native 双文本切换动效Toggle 实现方案

你可以直接用React Native自带的Animated API实现该需求,无需引入第三方依赖,以下是可直接运行的实现代码:

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

const ToggleButton = () => {
  // 定义选中状态:buy=买入 sell=卖出
  const [selected, setSelected] = useState<'buy' | 'sell'>('buy');
  // 动画值:控制滑块位移
  const slideAnim = useRef(new Animated.Value(0)).current;

  // 切换触发逻辑
  const handleToggle = (type: 'buy' | 'sell') => {
    if (type === selected) return;
    setSelected(type);
    // 执行平移动画,150ms时长平滑过渡
    Animated.timing(slideAnim, {
      toValue: type === 'buy' ? 0 : 120, // 120是单个选项的宽度,可自行调整
      duration: 150,
      useNativeDriver: false
    }).start();
  };

  return (
    <View style={styles.toggleContainer}>
      {/* 滑动选中背景 */}
      <Animated.View 
        style={[
          styles.slider,
          {
            transform: [{ translateX: slideAnim }]
          }
        ]} 
      />
      {/* 买入选项 */}
      <TouchableOpacity 
        style={styles.option}
        onPress={() => handleToggle('buy')}
        activeOpacity={0.7}
      >
        <Text style={[
          styles.optionText,
          selected === 'buy' ? styles.selectedText : styles.unselectedText
        ]}>
          买入
        </Text>
      </TouchableOpacity>
      {/* 卖出选项 */}
      <TouchableOpacity 
        style={styles.option}
        onPress={() => handleToggle('sell')}
        activeOpacity={0.7}
      >
        <Text style={[
          styles.optionText,
          selected === 'sell' ? styles.selectedText : styles.unselectedText
        ]}>
          卖出
        </Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  toggleContainer: {
    width: 240,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#f5f5f5',
    flexDirection: 'row',
    position: 'relative',
    padding: 2
  },
  slider: {
    position: 'absolute',
    width: 116,
    height: 36,
    borderRadius: 18,
    backgroundColor: '#fff',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 2
  },
  option: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1
  },
  optionText: {
    fontSize: 14,
    fontWeight: '500'
  },
  selectedText: {
    color: '#1890ff'
  },
  unselectedText: {
    color: '#666'
  }
});

export default ToggleButton;

自定义调整说明

  • 可以修改toggleContainer的宽高、背景色匹配你的设计稿
  • 调整动画duration参数修改动画速度
  • 修改slider的样式可以更换选中块的外观,比如换成渐变色、调整圆角等
  • 如果需要适配不同屏幕宽度,可以把滑块位移的目标值换成动态计算的容器宽度的一半,不用写死固定值

参考设计图:
设计参考图

内容的提问来源于stack exchange,提问作者Sufail Kalathil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:54:03