使用classList在React

时间:2019-01-08 21:02:12

标签: reactjs react-hooks

在我的组件中,我有一个useEffect钩子将事件侦听器添加到range函数中,以改变滑块的颜色。我只能在整个地方使用粉红色,而在滑块的错误一端只能使用蓝色。

在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>

1 个答案:

答案 0 :(得分:1)

不建议直接用React操作dom。您可以将输入值置于ur组件状态,而类可以根据状态成为输出

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'
  }
  ...
}