为 Android 上的 React Native Switch 选择不同的拇指颜色



我有以下组件:

<Switch trackColor={{true: COLORS.accent, false: COLORS.grey}} style={styles.switch} value={this.state.notifyOnEntry} onValueChange={(value) => {this.onToggle('notifyOnEntry', value)}} />

我想更改thumbColor并在启用或禁用时将其设置为两种不同的颜色,就像我为 trackColor 所做的那样。我以为这和trackColor一样,但thumbColor是单一的颜色而不是物体。

可以改变它吗?

您可以通过如下所示的条件提供颜色

import React, { useState } from "react";
import { View, Switch, StyleSheet } from "react-native";
export default function App() {
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
return (
<View style={styles.container}>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? COLORS.accent : COLORS.grey}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
</View>
);
}

您还可以对条件使用 notifyOnEntry,而不是启用值。

最新更新