最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How pass React prop to CSS - Stack Overflow

programmeradmin3浏览0评论

I have a problem - I don't know how to change checkbox color using a color value from props. My idea was to give it via style attribute but I don't know how to toggle this. I'm using rc-switch and I want to change his background depending on Switch state. I have something like this now

<Switch style={{ backgroundColor: mainColor }}/>

I have a problem - I don't know how to change checkbox color using a color value from props. My idea was to give it via style attribute but I don't know how to toggle this. I'm using rc-switch and I want to change his background depending on Switch state. I have something like this now

<Switch style={{ backgroundColor: mainColor }}/>

but it set this color for both states and I want this swich to bee 'defaultColor' when is in off position.

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jul 2, 2017 at 18:49 Alan WołejkoAlan Wołejko 4522 gold badges5 silver badges21 bronze badges 1
  • There is no style prop on the Switch Component, but there is a className prop, which you can use to add your custom class. – webdeb Commented Jul 2, 2017 at 18:53
Add a ment  | 

2 Answers 2

Reset to default 8

There is no style prop on the Switch Component, but there is a className prop, which you can use to add your custom class.

If you are using sass:

.mySwitch {
  &-black {
    background-color: black;
  }

  &-yellow {
    background-color: yellow;
  }
}

Then programatically switch the class.

<Switch className={`mySwitch-${color}` ... />

Could be an option, I think.

You have to pass a callback to your <Switch> ponent and then handle that event. You could write a ponent that wraps the original <Switch> and switches color when it's state changes. It could look like this:

import React from 'react';
import Switch from 'rc-switch';

class ColorChangingSwitch extends React.Component {
  constructor(props) {
    super(props);

    const {checked, defaultChecked} = props;
    this.state = {
      checked: checked || defaultChecked || false;
    }
  }

  onChange = (checked) => {
      // update your state
      this.setState({
      checked: checked,
    });
    this.props.onChange(checked);
  }

  render() {
    const {onChange, className, checked, ...otherProps} = this.props;
    const colorClassName = this.state.checked ? 'green' : 'red';

    return (
      <Switch
        {...otherProps}
        onChange={this.onChange}
        checked={checked}
        className={`${className} ${colorClassName}`}
      />
    );
  }
}

export default ColorChangingSwitch;

This is just a basic example. I didn't test it. You can still pass onChange to that ponent and react to it with whatever you want. Also you could add a prop that defines which colors/classes it should set depending on it's state instead of hardcoding them.

发布评论

评论列表(0)

  1. 暂无评论