首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用classList添加和删除react时出现问题

在使用classList添加和删除react时出现问题
EN

Stack Overflow用户
提问于 2019-01-08 21:02:12
回答 1查看 3.6K关注 0票数 0

在我的组件中,我让useEffect钩子将事件侦听器添加到range函数中,以便对滑块的颜色进行粉刷。我只能得到粉红色的工作各地,蓝色在错误的一端滑块。

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

组件

代码语言:javascript
复制
  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

代码语言:javascript
复制
  <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-08 21:43:09

不建议直接使用React操作dom。您可以将输入值放入您的组件状态,并且类可以是一个输出,这取决于状态。

代码语言:javascript
复制
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实现为返回类名的函数。

代码语言:javascript
复制
function getClassNameFnc(v, min, max) {
  if(v > max * 0.20) {
    return 'pink'
  }
  ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54099639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档