解决 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)=>{}} />
相关推荐
前端小D5 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
大龄秃头程序员6 天前
从源码里看懂 React Native 新架构:TurboModule 与 Fabric 到底是怎么跑起来的?
react native
前端小D7 天前
React Native Android 项目搭建
android·react native·react.js
hhhjhl9 天前
React Native 三方库「react-native-sha256」的鸿蒙化适配指南
react native·华为·harmonyos
2601_949970699 天前
React Native 三方库「react-native-version-check」的鸿蒙化适配指南
react native·华为·harmonyos
hhhjhl9 天前
React Native 三方库「react-native-proximity」的鸿蒙化适配指南
react native·华为·harmonyos
2601_949970699 天前
React Native 三方库「react-native-media-notification」的鸿蒙化适配指南
react native·华为·harmonyos
GitCode官方9 天前
从大语言模型到具身智能:百度百舸 LoongForge 入驻 AtomGit
人工智能·react native·百度·harmonyos·atomgit
2501_9159184112 天前
Windows 上开发 React Native iOS,真机调试、Fast Refresh 与打包 ipa
windows·vscode·react native·ios·个人开发·swift·敏捷流程
2501_9481226313 天前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado