解决 RN Switch 组件在安卓端样式很丑的问题

解决此种问题的方式有很多

  • 可以导入原生库react-native-switch

  • 切图 (会缺少动画)

  • 使用 js 组件

这里使用 js 绘制组件(原生体验)解决此类问题

Switch.tsx

tsx 复制代码
import React, { useEffect, useRef, useState } from 'react';
import { Animated, Pressable, StyleSheet } from 'react-native';

interface SwitchProps {
  value?: boolean;
  onChange?: (value: boolean) => void;
}

const Switch: React.FC<SwitchProps> = ({ value = false, onChange }) => {
  const switchAnim = useRef(new Animated.Value(0)).current;
  const switchHandle = () => {
    onChange?.(!value);
  };

  useEffect(() => {
    const toValue = value ? 23 : 3;
    Animated.timing(switchAnim, {
      toValue,
      duration: 100,
      useNativeDriver: false, // 此处原生驱动会导致 ios 颜色显示不对
    }).start();
  }, [switchAnim, value]);

  const backgroundColor = switchAnim.interpolate({
    inputRange: [0, 25],
    outputRange: ['#D2D2D2', '#904FF5'],
  });

  return (
    <Pressable onPress={switchHandle}>
      <Animated.View style={[styles.radioContainer, { backgroundColor }]}>
        <Animated.View style={[styles.radio, { transform: [{ translateX: switchAnim }] }]} />
      </Animated.View>
    </Pressable>
  );
};

const styles = StyleSheet.create({
  radioContainer: {
    width: 52,
    height: 32,
    borderRadius: 17,
    justifyContent: 'center',
    marginRight: 5,
  },
  radio: {
    width: 25,
    height: 25,
    backgroundColor: '#FFFFFF',
    borderRadius: 15,
  },
});

export default (props: SwitchProps) => {
  const [value, setValue] = useState(props.value || false);

  // 监听 props.value 的变化并更新内部状态
  useEffect(() => {
    setValue(props.value ?? false);
  }, [props.value]);

  return (
    <Switch
      value={value}
      onChange={() => {
        props.onChange?.(!value);
      }}
    />
  );
};

用法

tsx 复制代码
<Switch value={value} onChange={(value: boolean)=>{}} />
相关推荐
sure2823 小时前
react native 编写一个歌词组件
前端·react native
风景_fengjing18 小时前
React Native + Expo搭建APP项目+安卓模拟器
react native·expo
pe7er3 天前
Reactnative 项目开发(最佳?)实践
react native
每天开心3 天前
从零开始:使用 Expo 构建你的第一个 React Native 应用
react native
冯志浩3 天前
React Native 状态管理 - useState
react native·掘金·金石计划
wayne2143 天前
ReactNative0.81版本发布
react native
木西4 天前
React Native DApp 开发全栈实战·从 0 到 1 系列(expo-router)
react native·web3·app
pe7er5 天前
React Native 多环境配置全攻略:环境变量、iOS Scheme 和 Android Build Variant
前端·react native·react.js
麦客奥德彪9 天前
解决 React Native iOS 与 OpenHarmony 开发环境冲突问题
react native·ios·harmonyos