在关闭反应原点时改变Switch的颜色

Ank*_*shi 9 javascript react-native

我正在使用react native switch组件,我想在关闭时改变开关的颜色.

我可以添加onTintColor属性来在打开时更改颜色.

关闭时有没有办法改变颜色?

小智 14

不推荐使用onTintColor,请尝试以下方法。

  <Switch 
      trackColor={{true: 'red', false: 'grey'}}
      onValueChange={this.toggleSwitch}
      value={true}/>
Run Code Online (Sandbox Code Playgroud)

这有效

  • 在 Android(react-native 0.61.5)上,它会给出一个绿色的拇指圆圈(这很糟糕) (3认同)

ime*_*nox 7

只需添加:

style={{backgroundColor: '#FF0000', borderRadius: 17}}
Run Code Online (Sandbox Code Playgroud)

到Switch


Mih*_*hir 6

React native ColorSwitchExample在他们的文档中有。您可以在这里引用相同的内容。祝好运!

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Bha*_*han 6

我设计了特定于平台的开关,也使用了基于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)            }
/>
Run Code Online (Sandbox Code Playgroud)

内联边框样式

const inline_styles = StyleSheet.create({
switchEnableBorder: {
borderColor: '#6fa6d3',
borderWidth: 1},

switchDisableBorder: {
borderColor: '#f2f2f2',
borderWidth: 1,  },});
Run Code Online (Sandbox Code Playgroud)

Android输出:安卓系统 iOS输出: 的iOS

  • 很疯狂的是,“Switch”允许“trackColor”使用独立的开/关颜色,但不允许“thumbColor”使用独立的开/关颜色,即使如果您不指定自定义颜色,拇指将有两种不同的开/关颜色。 (4认同)

Yar*_*ski 5

对于来自 Google 的任何人:特别是对于 iOS,您需要使用以下ios_backgroundColor属性:

<Switch ios_backgroundColor="red" trackColor={{ true: 'blue', false: 'red' }} />
Run Code Online (Sandbox Code Playgroud)

参考:

https://facebook.github.io/react-native/docs/switch.html#trackcolor

https://facebook.github.io/react-native/docs/switch#ios-backgroundcolor