简体   繁体   English

如何将React prop传递给CSS

[英]How pass React prop to CSS

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. 我的想法是通过style属性给它,但我不知道如何切换它。 I'm using rc-switch and I want to change his background depending on Switch state. 我正在使用rc-switch,并且我想根据Switch状态更改他的背景。 I have something like this now 我现在有这样的事情

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

but it set this color for both states and I want this swich to become 'defaultColor' when is in off position. 但是它为两种状态都设置了这种颜色,并且我希望此夹层在关闭位置时变为“ defaultColor”。

There is no style prop on the Switch Component, but there is a className prop, which you can use to add your custom class. 开关组件上没有样式属性,但是有className属性,可用于添加自定义类。

If you are using sass: 如果您使用的是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> component and then handle that event. 您必须将回调传递给<Switch>组件,然后处理该事件。 You could write a component that wraps the original <Switch> and switches color when it's state changes. 您可以编写一个包装原始<Switch>并在其状态更改时切换颜色的组件。 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 component and react to it with whatever you want. 您仍然可以将onChange传递给该组件,并根据需要进行响应。 Also you could add a prop that defines which colors/classes it should set depending on it's state instead of hardcoding them. 您还可以添加一个prop,该prop定义应根据其状态设置的颜色/类,而不是对其进行硬编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM