【发布时间】:2016-08-26 06:28:37
【问题描述】:
我正在使用 react native switch 组件,我想在关闭它时更改开关的颜色。
我可以添加onTintColor属性来改变它开启时的颜色。
有什么方法可以在关闭时更改颜色?
【问题讨论】:
我正在使用 react native switch 组件,我想在关闭它时更改开关的颜色。
我可以添加onTintColor属性来改变它开启时的颜色。
有什么方法可以在关闭时更改颜色?
【问题讨论】:
onTintColor 已被弃用,请尝试以下操作。
<Switch
trackColor={{true: 'red', false: 'grey'}}
onValueChange={this.toggleSwitch}
value={true}/>
这行得通
【讨论】:
我设计了特定于平台的开关,还使用了基于 On Off 状态的边框。
<Switch
trackColor={{ true: '#7ab8e1', false: Platform.OS=='android'?'#d3d3d3':'#fbfbfb' }}
thumbColor={[Platform.OS=='ios'?'#FFFFFF':(item.status ?'#7ab8e1':'#ffffff')]}
ios_backgroundColor="#fbfbfb"
style={[item.status ?inline_styles.switchEnableBorder:inline_styles.switchDisableBorder]}
value={item.status}
onValueChange={() =>this.change_status(index) }
/>
内嵌边框样式
const inline_styles = StyleSheet.create({
switchEnableBorder: {
borderColor: '#6fa6d3',
borderWidth: 1},
switchDisableBorder: {
borderColor: '#f2f2f2',
borderWidth: 1, },});
【讨论】:
Switch 允许为trackColor 提供独立的开/关颜色,但thumbColor 不允许独立开/关颜色,尽管如果您这样做,拇指将有两种不同的开/关颜色,这很疯狂不指定自定义颜色。
只需添加:
style={{backgroundColor: '#FF0000', borderRadius: 17}}
到交换机
【讨论】:
React Native 在他们的文档中有ColorSwitchExample。您可以参考相同的here。祝你好运!
class ColorSwitchExample extends React.Component {
state = {
colorTrueSwitchIsOn: true,
colorFalseSwitchIsOn: false,
};
render() {
return (
<View>
<Switch
onValueChange={(value) => this.setState({colorFalseSwitchIsOn: value})}
onTintColor="#00ff00"
style={{marginBottom: 10}}
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorFalseSwitchIsOn} />
<Switch
onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})}
onTintColor="#00ff00"
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorTrueSwitchIsOn} />
</View>
);
}
}
【讨论】:
对于来自 Google 的任何人:
特别是对于 iOS,您需要使用 ios_backgroundColor 属性:
<Switch ios_backgroundColor="red" trackColor={{ true: 'blue', false: 'red' }} />
参考资料:
https://facebook.github.io/react-native/docs/switch.html#trackcolor
https://facebook.github.io/react-native/docs/switch#ios-backgroundcolor
【讨论】:
您可以使用 Mihir 提供的示例,这应该适用于 iOS。如果你想要使用 Material Design 并且在 Android 和 iOS 上都可以使用的东西(在撰写本文时,React-Native 不允许重新着色 Android 开关),你可以试试这个包:
https://github.com/recr0ns/react-native-material-switch
祝你好运!
【讨论】:
<Switch
trackColor={{true: '#3bde50', false: '#f5f6fc'}}
thumbColor='#FFF'
onValueChange={() => this.toggleSwitch(item, index)}
value={this.state.isActive}
/>
【讨论】:
这是来自docs 的示例,也可以动态更改拇指颜色:
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
【讨论】:
<Switch
ios_backgroundColor={Colors.secondaryTextColor}
thumbColor={[Platform.OS=='ios'?'white': 'white']}
trackColor={{ true: Colors.primaryColor, false: Colors.secondaryTextColor }}
style={{ transform: [{ scaleX: .7 }, { scaleY: .7 }] }}
value={this.state.toggleChatSwitch}
onValueChange={() => this.onChatSwitchPressed()}
/>
【讨论】: