【问题标题】:How to change slider-thumb color using React如何使用 React 更改滑块拇指颜色
【发布时间】:2019-04-12 03:19:19
【问题描述】:

这是我的实际输入范围:

这就是我想要的:

还有this is my code

RangeComponent.tsx

const active = '#64c3ef'
const inactive = '#dbdbdb'

export class RangeComponent extends React.Component<Props> {
  inputRef: any = React.createRef()

  state = { value: 10 }

  handleChange = (min: number, max: number) => (event: any) => {
    const value = event.target.value
    const progress = (value / max) * 100 + '%'
    this.setState({ value: value })
    const newBackgroundStyle = `linear-gradient(90deg, ${active} 0% ${progress}%, ${inactive} ${progress}% 100%)`
    this.inputRef.current.style.background = newBackgroundStyle
  }

  render() {
    const minValue = 10 
    const maxValue = 300
    const progress = (this.state.value / maxValue) * 100 + '%'

    const styleInput = {
      background: `linear-gradient(90deg, ${active} 0% ${progress}%, ${inactive} ${progress}% 100%)`,
    }

    return (
      <div>
        <input
          ref={this.inputRef}
          id="sliderId"
          className="inputR"
          name="sliderName"
          type="range"
          min={minValue}
          max={maxValue}
          value={this.state.value}
          onChange={this.handleChange(minValue, maxValue)}
          style={styleInput}
        />
        <div className="label">
          {this.state.value}
        </div>
      </div>
    )
  }
}

style.css

.inputR::-webkit-slider-thumb {
    background: rgba(255, 208, 255, 0.75);
}

如果可能,我想不在 style.css 中而是在 RangeComponent.tsx 中控制拇指颜色。

我不明白为什么 inputR 类对输入样式没有影响。 如何使用 javascript 对象 (styleInput) 中的 CSS 更改样式?

【问题讨论】:

  • 能不能上传到github或者codepen,我们看看?还请包括“滑块”类的 css。
  • @Francois 当然!我添加了一个 Codepen 链接:codepen.io/mistochi/pen/YMQZKV
  • 谢谢,我去看看。我目前正在使用移动设备。

标签: javascript reactjs typescript input


【解决方案1】:

所以首先回答你的最后一个问题:“为什么类 inputR 对输入样式没有影响。”

第一部分是为了设置滑块/拇指的样式,您需要设置“外观:无”。请记住添加 -webkit-appearance 以获得跨浏览器支持。这将有效地使滑块/拇指不可见,以便您重新设置样式。对 inputR 和 inputR::-webkit-slider-thumb 执行此操作。 (See codepen solution)

第二部分是虽然你可以做.inputR {-webkit-appearance: none}

在 CSS 或 const styleInput = { WebkitAppearance: 'none' }

在 JSX 中, 你不能在 JSX 中做伪类,例如。 .inputR::-webkit-slider-thumb {} 。您需要这样做才能为拇指设置样式。

我的建议是您在 CSS 中为滑块/拇指设置基本样式,然后通过内联样式或作为样式对象执行动态部分。(See codepen solution)

接下来要查看的是线性渐变。您正在使用变量 progress 并添加一个“%”符号。 const styleInput = { background:linear-gradient(90deg, ${active} 0% ${progress}%, ${inactive} ${progress} % 100%), }

但在您的代码中,您已经将“%”添加到 progress 中。 const progress = (value / max) * 100 + '%' 因此字符串文字解析为 100%% 并且您的渐变不会呈现。我从样式对象中删除了“%”(See codepen solution

希望对你有帮助,如果有什么不清楚的地方请告诉我。

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 2019-11-13
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 2020-01-16
    相关资源
    最近更新 更多