我遇到问题 - 我不知道如何使用道具的颜色值更改复选框的颜色。我的想法是通过样式属性给它,但我不知道如何切换这个。我正在使用rc-switch,我想根据开关状态更改他的背景。我有这样的事情现在如何将React prop传递给CSS
<Switch style={{ backgroundColor: mainColor }}/>
但是设置这个颜色两种状态,我想是在关闭位置时,该SWICH成为“defaultColor”。
我遇到问题 - 我不知道如何使用道具的颜色值更改复选框的颜色。我的想法是通过样式属性给它,但我不知道如何切换这个。我正在使用rc-switch,我想根据开关状态更改他的背景。我有这样的事情现在如何将React prop传递给CSS
<Switch style={{ backgroundColor: mainColor }}/>
但是设置这个颜色两种状态,我想是在关闭位置时,该SWICH成为“defaultColor”。
Switch Component上没有样式道具,但是有一个className道具,您可以使用它来添加自定义类。
如果您使用的青菜:
.mySwitch {
&-black {
background-color: black;
}
&-yellow {
background-color: yellow;
}
}
然后编程切换类。
<Switch className={`mySwitch-${color}` ... />
可能是一个选项,我认为。
您必须将回调传递给您的<Switch>
组件,然后处理该事件。您可以编写一个包装原始<Switch>
的组件,并在状态发生变化时切换颜色。它可能看起来像这样:
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;
这只是一个基本的例子。我没有测试它。您仍然可以将onChange
传递给该组件并根据需要做出反应。你也可以添加一个道具,根据它的状态来定义它应该设置哪些颜色/类,而不是硬编码它们。
Switch Component上没有'style'道具,但有一个'className'道具,您可以使用它来添加自定义类。 – webdeb