【问题标题】:Trouble working with classList add and remove in react在反应中使用 classList 添加和删除时遇到问题
【发布时间】:2025-11-21 20:10:02
【问题描述】:

在我的组件中,我有 useEffect 钩子将事件侦听器添加到范围函数,以便更改滑块的颜色。我只能让粉红色在所有地方都可以工作,而蓝色则在滑块的错误端。

在 console.log() 中,我看到了所有列出的类,但似乎只有粉色有效。谢谢。

组件

  const range = (r) => {
    // move gradient
    r.addEventListener('input', () => {
      // Change slide thumb color on way up
      if (r.value > r.max * 0.20) {
        r.classList.add('pink')
      }
      if (r.value > r.max * 0.40) {
        r.classList.add('purple')
      }
      if (r.value > r.max * 0.60) {
        r.classList.add('ltpurple')
      }
      if (r.value > r.max * 0.80) {
        r.classList.add('blue')
      }

      // Change slide thumb color on way down
      if (r.value < r.max * 0.20) {
        r.classList.remove('pink')
      }
      if (r.value < r.max * 0.40) {
        r.classList.remove('purple')
      }
      if (r.value < r.max * 0.60) {
        r.classList.remove('ltpurple')
      }
      if (r.value < r.max * 0.80) {
        r.classList.remove('blue')
      }
      // window.requestAnimationFrame(r)
      console.log(r.classList)
    })
  }

  useEffect(() => {
    Array.from(document.getElementsByClassName('range')).map(r => range(r))
  })

JSX

  <div className="row">
        <h3>Grooming</h3>
        <p>Care and health: hair, ears, mouth, nose, lips, face, hands, nails, feet, toes.</p>
        <input type="range" className="range blue"
          min={0} max={100} name="grooming" onBlur={handleBlur} />
        <p>Well groomed: hair, nails, ears, face, hands.</p>
      </div>
      <div className="row">
        <h3>Hygiene</h3>
        <p>Hygiene education and awareness. Routine and other daily practices.</p>
        <input type="range" className="range blue" onBlur={handleBlur}
          min={0} max={100} name="hygiene" />
        <p>Demonstrates appropriate hygiene practices.</p>
      </div>

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    不建议直接使用 React 操作 dom。您可以将输入值放在您的组件状态中,并且类可以根据状态作为输出

    const [v, setV] = useState(0)
    
    return (
      <div className="row">
            <h3>Grooming</h3>
            <p>Care and health: hair, ears, mouth, nose, lips, face, hands, nails, feet, toes.</p>
            <input type="range" value={v} onChange={e => setV(e.target.value)} className={getClassNameFnc(v, 0, 100)}
              min={0} max={100} name="grooming" onBlur={handleBlur} />
            <p>Well groomed: hair, nails, ears, face, hands.</p>
          </div>
    )
    

    将 getClassNameFnc 实现为返回类名的函数,例如

    function getClassNameFnc(v, min, max) {
      if(v > max * 0.20) {
        return 'pink'
      }
      ...
    }
    

    【讨论】:

      最近更新 更多