如何根据元素本身的值设置样式?

时间:2019-01-23 18:13:24

标签: javascript reactjs sass

我有一个<input>的映射数组,它们设置为type =“ range”。我可以使用Sass为它们设置样式,使它们看起来像我想要的,但是我也希望样式可以根据输入的自身值进行更改。

<div>
    <input
        id={"ts-" + index}
        className="trinary-toggle"
        type="range"
        min="-1"
        max="1"
        step="1"
        value=this.handleValue()
        onChange={(event) => {
            let thisSwitch = document.getElementById("ts-" + index);
            //unsure of what to do here. thisSwitch is undefined
        }}
    />
</div>

以及用于对相关部分进行样式设置的scss

.trinary-toggle::-webkit-slider-runnable-track {
    background: #CCCCCC;
}

如何根据输入的值更改“ trinary-toggle ::-webkit-slider-runnable-track”的背景样式?

1 个答案:

答案 0 :(得分:1)

建议不要创建多个类,而是根据输入的值应用正确的类,而不是动态修改样式。

这是一个简单的示例:

const ternarySliderClasses = ["trinary-toggle-red", "trinary-toggle-yellow", "trinary-toggle-green"];

class TernarySlider extends React.Component {
  state = { value: 0 };

  render() {
    const value = this.state.value;
    const stateClass = ternarySliderClasses[+value + 1];
    return ( 
      <input
        className={classNames('trinary-toggle', stateClass)}
        value={value}
        type="range"
        min="-1"
        max="1"
        step="1"
        onChange={this.handleChange}
      />
    );
  }

  handleChange = (event) => {
    this.setState({
      value: event.target.value
    });
  };
}

ReactDOM.render(<TernarySlider /> , document.getElementById("root"));
.trinary-toggle::-webkit-slider-runnable-track,
.trinary-toggle::-moz-range-track {
  border: 1px solid #333;
}

.trinary-toggle-red::-webkit-slider-runnable-track,
.trinary-toggle-red::-moz-range-track {
  background: #F00;
}

.trinary-toggle-yellow::-webkit-slider-runnable-track,
.trinary-toggle-yellow::-moz-range-track {
  background: #FF0;
}

.trinary-toggle-green::-webkit-slider-runnable-track,
.trinary-toggle-green::-moz-range-track {
  background: #0F0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.5/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />