在反应中使用 classList 添加和删除时遇到问题

Trouble working with classList add and remove in react

在我的组件中,我使用 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>

不推荐直接用React操作dom。您可以将输入值放入您的组件状态,并且 class 可以是输出,具体取决于状态

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 实现为 returns class 名称的函数,例如

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